高级的 文件、文件夹、压缩包 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
import shutil
f1 = open("a.txt", encoding="utf-8")
f2 = open("b.txt", "w", encoding="utf-8")
shutil.copyfileobj(f1, f2)
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
shutil.copyfile(src, dst)
import shutil
shutil.copyfile("a.txt", "b.txt")
shutil.copymode(src, dst)
import shutil
shutil.copymode("a.txt", "b.txt")
shutil.copystat(src, dst)
import shutil
shutil.copystat("a.txt", "b.txt")
shutil.copy(src, dst)
import shutil
shutil.copy("a.txt", "b.txt")
shutil.copy2(src, dst)
import shutil
shutil.copy2("a.txt", "b.txt")
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
例如:copytree(source, destination, ignore=ignore_patterns(‘*.pyc‘, ‘tmp*‘))
import shutil
shutil.copytree("a", "b")
shutil.rmtree(path[, ignore_errors[, onerror]])
import shutil
shutil.rmtree(b")
shutil.move(src, dst)
import shutil
shutil.move("a.txt", "b.txt")
shutil.make_archive(base_name, format,...)
base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
如:www =>保存至当前路径
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户,默认当前用户
group: 组,默认当前组
logger: 用于记录日志,通常是logging.Logger对象
#将 /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‘)
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()
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()
原文:https://www.cnblogs.com/evescn/p/13622148.html