• Python Cookbook (2) 文件


    1. Python对文件的支持
    1) 内建的open函数等
    2) os
    3) 第三方工具
    有些语言的特点就是很容易支持第三方

    2. Python中的大多数文件接口都是跨平台的。这种设计的重要性怎么赞美也不为过。

    3. Python的文件处理接口往往并不局限在只用于真实的物理文件,只要目标对象实现了期望的协议,一切工作都可以平滑自然地进行。

    4. 大文件的时候怎么处理?

    5. open 的读取模式
    r 以文本读取,默认,不用指定
    rb 以二进制读取
    w 以文本模式写
    wb 以二进制写
    rU 同r,但是考虑了不用平台的\n,用这个就对了

    Example:

     1 def test_file():
     2     filename = "./main.py"
     3     infile = open(filename, 'rU');
     4     try:
     5         #for line in infile:
     6         lines = len(infile.readlines())
     7         print "{0}(line={1})".format(filename, lines);
     8     finally:
     9         infile.close()
    10     infile.close()
    11     
    12     outfilename = "./testfile.txt"
    13     outfile = open(outfilename, 'w')
    14     outfile.write("This is a test file");
    15     outfile.close()

    tar 工具

     1 #!/usr/local/bin/python
     2 
     3 import os
     4 import tarfile
     5 import sys
     6 
     7 def make_tar(folder_to_backup, dest_folder='.', compression='gz'):
     8     if compression:
     9         dest_ext='.'+compression
    10     else:
    11         dest_ext=''
    12     arcname = os.path.basename(folder_to_backup)
    13     dest_name = '{0}.tar{1}'.format(arcname, dest_ext)
    14     dest_path = os.path.join(dest_folder, dest_name)
    15     if compression:
    16         dest_cmp = ':' + compression
    17     else:
    18         dest_cmp = ''
    19     
    20     out = tarfile.TarFile.open(dest_path, 'w'+dest_cmp)
    21     out.add(folder_to_backup, arcname)
    22     out.close()
    23     return dest_path
    24     
    25 def main():
    26     argc = len(sys.argv)
    27     folder_to_backup = ''
    28     dest_folder = ''
    29     compression = ''
    30        
    31     if argc == 2: 
    32         folder_to_backup = sys.argv[1]
    33         make_tar(folder_to_backup)
    34     
    35     elif argc == 3:
    36         folder_to_backup = sys.argv[1]
    37         dest_folder = sys.argv[2]
    38         make_tar(folder_to_backup, dest_folder)
    39     
    40     elif argc == 4:
    41         folder_to_backup = sys.argv[1]
    42         dest_folder = sys.argv[2]
    43         compression = sys.argv[3]
    44         make_tar(folder_to_backup, dest_folder, compression)
    45     else:
    46         print "Args wrong, ./mytar folder_to_backup [dest_folder [compression]]"
    47         return
    48     
    49     return
    50     
    51 main()
  • 相关阅读:
    距离某天还有多久
    U3D各键值说明
    一些比较重要的函数
    U3D功能脚本备忘
    沟边
    渲染排序
    字符串转整数备录
    沟边
    U3D优化
    Unity中的四个路径
  • 原文地址:https://www.cnblogs.com/xjsllll/p/2990783.html
Copyright © 2020-2023  润新知