shutil是一个用于简化文件操作的模块。
- 复制文件(传入源文件对象和目标文件对象)
import shutil
f1 = open(r'/Users/jingxing/PycharmProjects/day20/test.py', 'rb')
f2 = open(r'/Users/jingxing/PycharmProjects/day20/test_test.py', 'rb')
shutil.copyfileobj(f1, f2)
- 压缩文件
import shutil
shutil.make_archive('myzip', 'zip', r'/Users/jingxing/PycharmProjects/day20')
shutil.make_archive('mytar', 'tar', r'/Users/jingxing/PycharmProjects/day20')
- 解压文件
import shutil
shutil.unpack_archive(r'/Users/jingxing/PycharmProjects/day20/myzip.zip')
shutil.unpack_archive(r'/Users/jingxing/PycharmProjects/day20/mytar.tar')
其他两个用于解压的模块
zipfile
从名字可以看出来是解压zip压缩文件的模块。
- 解压
import zipfile
z = zipfile.ZipFile(r'/Users/jingxing/PycharmProjects/day20/myzip.zip', 'r')
z.extractall(path=r'/Users/jingxing/PycharmProjects/day20')
z.close()
- 往压缩包中添加文件
import zipfile
z = zipfile.ZipFile(r"/Users/jingxing/PycharmProjects/python全栈/day20/代码/my压缩.tar","w")
z.write("1.昨日回顾")
z.write("2.今日内容")
z.close()
tarfile
- 解压
import tarfile
t = tarfile.open(r"/Users/jingxing/PycharmProjects/python全栈/day20/代码/my压缩.tar","w")
t.extractall(r"/Users/jingxing/PycharmProjects/python全栈/day19")
t.close()
- 往压缩包中添加文件
port tarfile
t = tarfile.open(r"/Users/jingxing/PycharmProjects/python全栈/day20/代码/my压缩.tar","w")
t.add("1.昨日回顾")
t.add("2.今日内容")
t.close()