shutil模块拷贝与解压缩模块----day19

shutil模块
总结: shutil模块在 copy文件 压缩文件时 使用

是一个工具包,封装了高级模块操作,让你操作起来更加方便功能与os有些重叠,os只能帮你处理文件是否存在,路径是否正确等,无法直接完成copy等操作
还提供了压缩与解压缩

# 压缩文件 支持的格式 zip 和tar
shutil.make_archive("shutil模块",
"zip",
r"D:\脱产5期内容\day19",
"D:\脱产5期内容\day19\这是压缩后的文件")

# 解压缩
# shutil.unpack_archive(r"shutil模块.zip",
# r"D:\脱产5期内容\day19\shutil模块\解压的文件夹",
# r"zip")

将文件内容拷贝到另一个文件中

1 import shutil
2  
3 shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))

 

shutil.copyfile(src, dst)
拷贝文件

1 shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在

 

shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变

1 shutil.copymode('f1.log', 'f2.log') #目标文件必须存在

 

shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags

1 shutil.copystat('f1.log', 'f2.log') #目标文件必须存在

 

shutil.copy(src, dst)
拷贝文件和权限

1 import shutil
2  
3 shutil.copy('f1.log', 'f2.log')

 

shutil.copy2(src, dst)
拷贝文件和状态信息

1 import shutil
2  
3 shutil.copy2('f1.log', 'f2.log')

 

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

1 import shutil
2  
3 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除 
 拷贝软连接

 

shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件

1 import shutil
2  
3 shutil.rmtree('folder1')

 

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

1 import shutil
2  
3 shutil.move('folder1', 'folder3')
posted @ 2018-12-10 15:54  WenChen-0o0  阅读(177)  评论(0编辑  收藏  举报