python中shutil模块的使用

可以操作权限的处理文件模块:shutil

 

# 基于路径的文件复制

import shutil

shutil.copyfile("oldfile_path","newfile_path")

例:

# shutil.copyfile("a.txt","b.txt")

#基于文件流的文件复制

with open("oldfile_path","rb") as f, open("newfile_path","wb") as s:

  shutil.copyfileobj(f,s)

例:

# with open("a.txt","rb") as f,open("b.txt","wb") as s:
# shutil.copyfileobj(f,s)

# 递归删除目标目录,无条件删除

shutil.rmtree("target_file")  

例:

# shutil.rmtree(r'C:UsersDELLPycharmProjectsuntitled1four weekmudule04	ext')

#文件移动,可重命名,会删除原文件,新路径需指定文件名

shutil.remove("old_path","new_path")

例:

# shutil.move("b.txt","text/b.txt")

# 文件夹压缩,不可压缩文件

shutil.make_achive("文件夹路径","格式format","压缩后的路径及包名")

例:

# shutil.make_archive("text","zip",r"C:UsersDELLPycharmProjectsuntitled1four weekmudule04")

# 文件夹解压

shutil.unpack_archive("压缩包路径","解压后的路径及创建的文件夹名","格式format")

例:

# shutil.unpack_archive("text.zip","text","zip")
原文地址:https://www.cnblogs.com/dongxixi/p/10690890.html