Python shutil模块用法实例分析
本文主要介绍了Python shutil模块用法,结合实例形式分析了Python使用shutil模块操作文件拷贝的相关实现技巧与注意事项,需要的朋友可以参考下: shutil模块 主要作用与拷贝文件用的。 1.shutil.copyfileobj(文件1,文件2):将文件1的数据覆盖copy给文件2。 1 import shutil 2 f1 = open("1.txt",encoding="utf-8") 3 f2 = open("2.txt","w",encoding="utf-8") 4 shutil.copyfileobj(f1,f2) 2.shutil.copyfile(文件1,文件2):不用打开文件,直接用文件名进行覆盖copy。 1 import shutil 2 shutil.copyfile("1.txt","3.txt") 3.shutil.copymode(文件1,文件2):之拷贝权限,内容组,用户,均不变。 1 def copymode(src,dst): 2 """copy mode bits from src to dst""" 3 if hasattr(os,‘chmod‘): 4 st = os.stat(stc) 5 mode = stat.S_IMODE(st.st_mode) 6 os.chmod(dst,mode) 4.shutil.copystat(文件1,文件):只拷贝了权限。 在学习过程中有什么不懂得可以加我的 python学习交流扣扣qun,××× 群里有不错的学习视频教程、开发工具与电子书籍。 与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容 1 def copystat(src,dst): 2 """将所有的状态信息(模式位、时间、时间、标志)从src复制到dst""" 3 st = os.stat(src) 4 mode = stat.S_IMODE(st.st_mode) 5 if hasattr(os,‘utime‘): 6 os.utime(dst,(st.st_atime,st.st_mtime)) 7 if hasattr(os,‘chmod‘) 8 os.chmod(dst,mode) 9 if hasattr(os,‘chflags‘) and hasattr(st,‘st_flags‘): 10 try: 11 os.chflags(dst,st.st_flags) 12 except OSError,why: 13 for err in ‘EOPNOTSUPP‘,‘ENOTSUP‘: 14 if hasattr(errno,err) and why.errno == getattr(errno,err): 15 break 16 else: 17 raise 5.shutil.copy(文件1,文件2):拷贝文件和权限都进行copy。 1 def copy(src,dst): 2 """copy data and mode bits ("cp src dst") 3 The destination may be a directory. 4 """ 5 if os.path.isdir(dst): 6 dst = os.path.join(dst,os.path.basename(src)) 7 copyfile(src,dst) 8 copymode(src,dst) 6.shutil.copy2(文件1,文件2):拷贝了文件和状态信息。 7.shutil.copytree(源目录,目标目录):可以递归copy多个目录到指定目录下。
递归的去拷贝文件
8.shutil.rmtree(目标目录):可以递归删除目录下的目录及文件。 9.shutil.move(源文件,指定路径):递归移动一个文件。 10.shutil.make_archive():可以压缩,打包文件。 1 import shutil 2 shutil.make_archive("shutil_archive_test","zip","D:新建文件夹 (2)") 11.shutil.make_archive(base_name,format,...) 创建压缩包并返回文件路径,例如:zip、tar
1 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录 2 import shutil 3 ret = shutil.make_archive("wwwwwwwwww",‘gztar‘,root_dir=‘/Users/wupeiqi/Downloads/test‘) 4 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录 5 import shutil 6 ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww",root_dir=‘/Users/wupeiqi/Downloads/test‘) shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细: zipfile 压缩解压 1 import zipfile 2 # 压缩 3 z = zipfile.ZipFile(‘laxi.zip‘,‘w‘) 4 z.write(‘a.log‘) 5 z.write(‘data.data‘) 6 z.close() 7 # 解压 8 z = zipfile.ZipFile(‘laxi.zip‘,‘r‘) 9 z.extractall() 10 z.close() tarfile 压缩解压 1 import tarfile 2 # 压缩 3 tar = tarfile.open(‘your.tar‘,‘w‘) 4 tar.add(‘/Users/wupeiqi/PycharmProjects/bbs2.zip‘,arcname=‘bbs2.zip‘) 5 tar.add(‘/Users/wupeiqi/PycharmProjects/cmdb.zip‘,arcname=‘cmdb.zip‘) 6 tar.close() 7 # 解压 8 tar = tarfile.open(‘your.tar‘,‘r‘) 9 tar.extractall() # 可设置解压地址 10 tar.close() 第二种方法: 1 import zipfile 2 z = zipfile.ZipFile("day5.zip","w") 3 z.write("a") 解压: 1 z.extractall("a") 觉得文章还不错的话不妨收藏起来慢慢看,有任何建议或看法欢迎大家在评论区分享讨论! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |