• shutil 高级文件操作


      High-level file operations  高级的文件操作模块,官网:https://docs.python.org/2/library/shutil.html#
      os模块提供了对目录或者文件的新建/删除/查看文件属性,还提供了对文件以及目录的路径操作。比如说:绝对路径,父目录……  但是,os文件的操作还应该包含移动 复制  打包 压缩 解压等操作,这些os模块都没有提供。
      而本章所讲的shutil则就是对os中文件操作的补充。--移动 复制  打包 压缩 解压,

      注意即便是更高级别的文件复制函数(shutil.copy(),shutil.copy2())也不能复制所有文件的元数据。这意味着在POSIX平台上,文件的所有者和组以及访问控制列表都将丢失。在Mac OS中资源fork和其他元数据无法使用。这意味着资源将丢失,文件类型和创建者代码将不正确。在Windows上,文件所有者,ACL和备用数据流不会被复制。

    拷贝文件
    shutil.copyfile(src, dst):复制文件内容(不包含元数据)从src到dst。dst 必须是完整的目标文件名;拷贝目录参见shutil.copy()。如果src和dst是同一文件,就会引发错误shutil.Error。dst必须是可写的,否则将引发异常IOError。如果dst已经存在,它会被替换。特殊文件,例如字符或块设备和管道不能使用此功能,因为copyfile会打开并阅读文件。 src和dst的是字符串形式的路径名。

    copyfile()调用了底函数层copyfileobj()。
    shutil.copyfileobj(fsrc, fdst[, length]):复制文件内容(不包含元数据)从类文件对象src到类文件对dst。可选参数length指定缓冲区的大小,负数表示一次性读入。默认会把数据切分成小块拷贝,以免占用太多内存。注意:拷贝是从fsrc的当前文件开始。

    def copyfileobj(fsrc, fdst, length=16*1024):
        """copy data from file-like object fsrc to file-like object fdst"""
        while 1:
            buf = fsrc.read(length)
            if not buf:
                break
            fdst.write(buf)
    View Code

    shutil.copyfileobj(fsrc, fdst[, length])

    Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks.
    含义:拷贝fsrc类文件对象到fdst类文件对象

    shutil.copyfile(src, dst)
    Copy the contents (no metadata) of the file named src to a file named dst.
    含义:拷贝src文件内容(不包含元数据)到目标dst文件

    shutil.copytree(src, dst, symlinks=False, ignore=None)
    Recursively copy an entire directory tree rooted at src.
    含义:递归拷贝以src为根目录的整个目录树到目标目录

    shutil.rmtree(path[, ignore_errors[, onerror]])
    Delete an entire directory tree.
    含义:删除整个目录树

    shutil.move(src, dst)
    Recursively move a file or directory (src) to another location (dst).
    含义:移动一个文件或目录到另一个位置(同目录也可以用来修改名字)。

    shutil.copymode(src, dst)
    Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst are path names given as strings.
    含义:从源文件拷贝权限位到目标文件,文件内容、所有者、组不受影响。


    shutil.copystat(src, dst)
    Copy the permission bits, last access time, last modification time, and flags from src to dst. The file contents, owner, and group are unaffected.
    含义:从源文件拷贝权限位、最后访问时间、最后修改时间、flags到目标文件,文件内容、所有者、组不受影响。


    shutil.copy(src, dst)
    Copy the file src to the file or directory dst.
    含义:拷贝源文件到文件或目录。


    shutil.copy2(src, dst)
    Similar to shutil.copy(), but metadata is copied as well – in fact, this is just shutil.copy() followed by copystat(). This is similar to the Unix command cp -p.
    含义:和shutil.copy()相似,但是也会拷贝元数据,实际上只是调用shutil.copy()后接着调用copystart()。

    #!/usr/bin/python3 -B
    
    import shutil
    import os
    import datetime
    import subprocess
    
    
    def main():
        base_src_path = "/home/dsw/work/src"
        base_dst_path = "./backup"
        copy_dir = ["scene", "layer", "logic", "tools"]
        ignore_pattern = shutil.ignore_patterns("*.o", "*.a")
    
        if os.path.exists(base_dst_path):
            shutil.rmtree(base_dst_path)
        os.mkdir(base_dst_path)
    
        for entry in copy_dir:
            src = os.path.join(base_src_path, entry)
            dst = os.path.join(base_dst_path, entry)
            shutil.copytree(src, dst, ignore=ignore_pattern)
    
        t = datetime.datetime.now()
        tar_name = t.strftime("game-%m-%d-%H-%M.tar.gz")
        cmd = "tar -cf {0} ./backup/*".format(tar_name)
        subprocess.call(cmd, shell=True)
    
    if __name__ == '__main__':
        main()
    View Code

    压缩解压

    2.7以后的版本提供了压缩和解压功能。
    shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]]):创建归档文件(如ZIP或TAR),返回其名字。base_name文件名。format压缩格式,“zip”, “tar”, “bztar” or “gztar”。root_dir压缩的根目录。base_dir开始压缩的目录。root_dir 和 base_dir默认都是当前目录。所有者和组默认为当前用户和组;logger为logging.Logger的实例。
    shutil.get_archive_formats():返回支持的格式列表。默认支持:

    In [3]: shutil.get_archive_formats()
    Out[3]:
    [('bztar', "bzip2'ed tar-file"),
     ('gztar', "gzip'ed tar-file"),
     ('tar', 'uncompressed tar file'),
     ('zip', 'ZIP file')]

    通过使用register_archive_format()可以增加新格式。
    shutil.register_archive_format(name, function[, extra_args[, description]]):注册一个文件格式,不常用。
    shutil.unregister_archive_format(name):移除文件格式,不常用。

    压缩实例:

    #!/usr/bin/python3 -B
    
    import os
    from shutil import make_archive
    
    def main():
        make_archive("backup", 'tar', "/home/dsw/work")  #将/home/dsw/work目录下的文件备份
    
    if __name__ == '__main__':
        main()
    View Code
  • 相关阅读:
    js正则表达式 验证手机号,email地址和邮政编码
    XP系统中IIS访问无法显示网页,目前访问网站的用户过多。终极解决办法
    读《现代前端技术解析》有感
    开源一套基于vue全家桶的webapp
    canvas图像处理汇总
    chrome调试工具高级不完整使用指南(实战二)
    chrome调试工具高级不完整使用指南(实战一)
    chrome调试工具高级不完整使用指南(优化篇)
    chrome调试工具高级不完整使用指南(基础篇)
    前端项目怎样合理使用模块化和闭包?
  • 原文地址:https://www.cnblogs.com/DswCnblog/p/6139043.html
Copyright © 2020-2023  润新知