zoukankan      html  css  js  c++  java
  • 模块之shutil模块

    #利用shutill.copyfileobj  复制一个文件的内容到另一个文件里面

    #通过文件名字直接复制

    #附带目录里的内容一起copy

    #压缩指定文件到指定路径

    #shutil.copymode(srcdst)   只拷贝权限,内容 组 用户均不变(目标文件必须存在)

    # shutil.start  (src,dsc) 只拷贝状态信息  (目标文件必须存在)

    # shutil.copy(stc, dsc)  拷贝文件和权限

    # shutil.copy2(srtc, dsc)  拷贝文件和状态信息

    #shutil.ignore_patterns(*patterns)  递归的去拷贝文件

    #shutil.copytree(src, dst, symlinks=False, ignore=None)  递归的去拷贝文件

    #shutil.rmtree(path[,ignore_errors[,onerror]])    ignore是排除的意思  递归的去删除文件(父级目录要有可写权限)

    #shutil.move(src, dsc)  递归的去移动文件 它类似于‘mv ’ 其实就是重命名

    #shutil.make_archive(base_name, format...)  创建压缩包并返回路径   例如  zip ,tar

    shutil模块

     

    主要作用与拷贝文件用的。

    1.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)
    复制代码

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

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

     

    3.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)
    复制代码

    4.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
    复制代码

    5.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)
    复制代码

    6.shutil.copy2(文件1,文件2):拷贝了文件和状态信息。

     

    7.shutil.copytree(源目录,目标目录):可以递归copy多个目录到指定目录下。

    • shutil.ignore_patterns(*patterns)
    • shutil.copytree(src, dst, symlinks=False, ignore=None)

    递归的去拷贝文件

    例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

    8.shutil.rmtree(目标目录):可以递归删除目录下的目录及文件。

     

    9.shutil.move(源文件,指定路径):递归移动一个文件。

     

    10.shutil.make_archive():可以压缩,打包文件。

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

    11.shutil.make_archive(base_name, format,...)

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

      • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
        如:www                        =>保存至当前路径
        如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
      • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
      • root_dir: 要压缩的文件夹路径(默认当前目录)
      • owner: 用户,默认当前用户
      • group: 组,默认当前组
      • logger: 用于记录日志,通常是logging.Logger对象
    1
    2
    3
    4
    5
    6
    7
    8
    9
    #将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
      
    import shutil
    ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
      
      
    #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
    import shutil
    ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

    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()
    复制代码

    第二种方法:

    import zipfile
    
    z = zipfile.ZipFile("day5.zip","w")
    
    z.write("a")
  • 相关阅读:
    『转载』Git管理工具sourcetree安装与使用
    实用网站分享:全栈开发可能需要用到的网站
    低版本浏览器(IE6+)页面兼容性问题相关处理
    Git常用命令说明
    jquery的全局函数 多库并存
    深浅拷贝
    localStorage
    jquery中封装了三种ajax请求方式
    jquery的树状菜单
    自定义动画 jquery的结束动画
  • 原文地址:https://www.cnblogs.com/yuexijun/p/10087308.html
Copyright © 2011-2022 走看看