• shutil模块


    shutil:文件、文件夹、压缩包 处理模块

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

    将文件内容拷贝到另一个文件中,可以指定长度,需要注意的是fsrc和tdst都是文件对象,也就是需要将这两个文件都打开,意味着fdst必须先存在,相当麻烦

    import shutil
    shutil.copyfileobj(open('test.txt','r',encoding='utf-8'),open('new_test.txt','w',encoding='utf-8'))

    #windows环境下,写文件不指定编码格式会以操作系统默认格式写文件(GBK)

    试了下指定长度,发现指定与不指定结果都一样,没什么卵用。

    • shutil.copyfile(src, dst)

    拷贝文件,仅内容,比上一个先进,无需事先打开文件,先不管目标文件存不存在,不过在读格式和写格式上会有什么变化呢?将源文件编码改为ansi模式

    import shutil
    shutil.copyfile('test.txt','new_test.txt')

    通过执行操作发现源文件为GBK则复制过来还是GBK,这也正常,因此在特殊场景下可能还是要用到第一个方法。

    • shutil.copymode(src, dst):仅拷贝权限。内容、组、用户均不变,目标文件必须存在,这在linux下比较好使,对应st_mode的值
    • shutil.copystat(src, dst):仅拷贝状态的信息,包括:修改时间、访问时间、用户组,在windows下只观察到改了修改时间和访问时间
    • shutil.copy(src, dst):拷贝文件和权限
    • shutil.copy2(src, dst):拷贝文件和状态信息
    • shutil.copytree(src, dst, symlinks=False, ignore=None)

    递归的去拷贝文件夹

    shutil.ignore_patterns(*patterns) #结合递归命令

    import shutil

    shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) 

    #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除 .pyc mp类型的文件

    import shuti

    shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

    #f2相当于生成f1的快捷方式

    • rmtree(path, ignore_errors=False, onerror=None)

    递归的删除文件,是否忽略错误,错误处理的函数,见官方描述:

    If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func,path, exc_info) where func is platform and implementation dependent;path is the argument to that function that caused it to fail; and  exc_info is a tuple returned by sys.exc_info().  If ignore_errors is false and onerror is None, an exception is raised.   

    • shutil.move(src, dst):递归的去移动文件,它类似mv命令,其实就是重命名。
    • shutil.make_archive(base_name, format,...)

    创建压缩包并返回文件路径,例如:zip、tar

    创建压缩包并返回文件路径,例如:zip、tar

      1. base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
      2. 如 data_bak                       =>保存至当前路径
      3. 如:/tmp/data_bak =>保存至/tmp/
      4. format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
      5. root_dir: 要压缩的文件夹路径(默认当前目录)
      6. owner: 用户,默认当前用户
      7. group: 组,默认当前组
      8. logger: 用于记录日志,通常是logging.Logger对象

    #将 /data 下的文件打包放置当前程序目录
    import shutil
    ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
    #将 /data下的文件打包放置 /tmp/目录
    import shutil
    ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

    • shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

    import zipfile

    # 压缩
    z = zipfile.ZipFile('laxi.zip', 'w')
    z.write('a.log')
    z.write('data.data')
    z.close()

    
    

    # 解压
    z = zipfile.ZipFile('laxi.zip', 'r')
    z.extractall(path='.')
    z.close()

    
    

    import tarfile

    # 压缩
    >>> t=tarfile.open('/tmp/egon.tar','w')
    >>> t.add('/test1/a.py',arcname='a.bak')
    >>> t.add('/test1/b.py',arcname='b.bak')
    >>> t.close()


    # 解压
    >>> t=tarfile.open('/tmp/egon.tar','r')
    >>> t.extractall('/egon')
    >>> t.close()

     







  • 相关阅读:
    判断字符中是否包含汉字
    since I lived here; since I have lived here. 的区别? 从语法上看, 为啥会有这样的区别?
    have married; have been married; 到底是结婚了没?还是已经离婚了?
    C#项目依据 x86 x64 配置不同的引用
    现在完成时可以表示过去事件对现在的影响/效果. 过去完成时也可以起相同的作用!!!!
    使用现在完成时的常见错误(转发)
    去除win10下的缺省ctrl加空格功能
    appear + 表语 与 appear to be + "表语" 的区别; get hurt与 get to be hurt的区别
    ssm搭建的一个web应用的工作流程
    return和finally究竟谁先执行,还有return是怎么返回数据的
  • 原文地址:https://www.cnblogs.com/anner-nie/p/8492793.html
Copyright © 2020-2023  润新知