• (11)shutil模块(文件处理模块)


    shutil模块的格式

    shutil.copyfileobj(文件1,文件2)   #将文件1的数据覆盖copy给文件2 

    import shutil
    
    f1 = open("1.txt",encoding="utf-8")
    
    f2 = open("2.txt","w",encoding="utf-8")
    
    shutil.copyfileobj(f1,f2)

    PS:文件2必须存在,不存在报错

    shutil.copyfile(文件1,文件2)   #不用打开文件,直接用文件名进行覆盖copy

    import shutil
    
    shutil.copyfile("1.txt","3.txt")

    shutil.copymode(文件1,文件2):之拷贝权限,内容组,用户,均不变

    def copymode(src,dst):
        """copy mode bits from src to dst"""
        if hasattr(os,'chmod'):
            st = os.stat(stc)
            mode = stat.S_IMODE(st.st_mode)
            os.chmod(dst,mode)

    shutil.copystat(文件1,文件):只拷贝了权限

    def copystat(src,dst):
        """将所有的状态信息(模式位、时间、时间、标志)从src复制到dst"""
        st = os.stat(src)
        mode = stat.S_IMODE(st.st_mode)
        if hasattr(os, 'utime'):
            os.utime(dst,(st.st_atime,st.st_mtime))
        if hasattr(os, 'chmod')
            os.chmod(dst,mode)
        if hasattr(os, 'chflags') and hasattr(st,'st_flags'):
            try:
                os.chflags(dst, st.st_flags)
            except OSError,why:
                for err in 'EOPNOTSUPP', 'ENOTSUP':
                    if hasattr(errno,err) and why.errno == getattr(errno, err):
                        break
                    else:
                        raise

    shutil.copy(文件1,文件2):拷贝文件和权限都进行copy

    def copy(src,dst):
        """copy data and mode bits ("cp src dst")
        The destination may be a directory.
        """
        if os.path.isdir(dst):
            dst = os.path.join(dst,os.path.basename(src))
            copyfile(src,dst)
            copymode(src,dst)

    hutil.make_archive()   #可以压缩,打包文件

    import shutil
    
    shutil.make_archive("shutil_archive_test","zip","D:新建文件夹 (2)")

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

    zipfile 压缩解压

    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()
    z.close()

    tarfile 压缩解压

    import tarfile
    
    # 压缩
    tar = tarfile.open('your.tar','w')
    tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
    tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
    tar.close()
    
    # 解压
    tar = tarfile.open('your.tar','r')
    tar.extractall()  # 可设置解压地址
    tar.close()
  • 相关阅读:
    MSIL实用指南-加载null、string、long、float、double等值
    MSIL实用指南-加载int值
    MSIL实用指南-IL版hello world
    中文编程语言Z语言开源正式开源!!!
    Lisp永远成不了编程主流语言
    TKT中文编程语言简介
    Anaconda+django写出第一个web app(八)
    Anaconda+django写出第一个web app(七)
    Anaconda+django写出第一个web app(六)
    Anaconda+django写出第一个web app(五)
  • 原文地址:https://www.cnblogs.com/shizhengquan/p/10169694.html
Copyright © 2020-2023  润新知