1. shutil 模块的几个方法;2. zipfile 模块的几个方法;3. 归档与压缩
shutil
>>> import shutil # 下面的例子就不重复这个导入操作了
>>>
shutil.copy()
- 功能:复制文件
- 格式:
shutil.copy(来源路径, 目标路径)
- 返回值:目标路径
- 注意:在拷贝的同时,可以给文件重命名
>>> rst = shutil.copy(r"d:\tmp\text.txt", r"d:\tmp\test.txt")
>>> rst
\'d:\\tmp\\test.txt\'
>>>
shutil.copy2()
- 功能:复制文件,保留元数据(文件信息,如创建时间、最近保存时间等)
- 格式:
shutil.copy2(来源路径, 目标路径)
- 返回值:目标路径
- 注意:
copy 和 copy2 的唯一区别在于 copy2 复制文件时尽量保留元数据
>>> rst = shutil.copy2(r"d:\tmp\text.txt", r"d:\tmp\text.py")
>>> rst
\'d:\\tmp\\text.py\'
>>>
shutil.copyfile()
- 功能:将一个文件中的内容复制到另外一个文件中
- 格式:
shutil.copyfile(\'源路径\', \'目标路径\')
- 返回值:目标路径
- 注意:同名文件会被覆盖
>>> rst = shutil.copyfile(r"d:\tmp\text.py", r"d:\tmp\Python3\text.py")
>>> rst
\'d:\\tmp\\Python3\\text.py\'
>>>
shutil.move()
- 功能:移动
文件 或 文件夹
- 格式:
shutil.move(源路径, 目标路径)
- 返回值:目标路径
>>> rst1 = shutil.move(r"d:\tmp\text.txt", r"d:\tmp\Python3")
>>> rst1
\'d:\\tmp\\Python3\\text.txt\'
>>>
>>> rst2 = shutil.move(r"d:\tmp\Python2", r"d:\tmp\Python")
>>> rst2
\'d:\\tmp\\Python\\Python2\'
>>>
归档
shutil.make_archive()
- 功能:归档操作
- 格式:
shutil.make_archive(\'归档之后的目录和文件名\', \'后缀\', \'需要归档的文件夹\')
- 返回值:归档之后的地址
>>> rst = shutil.make_archive(r"d:\tmp\twofiles", "zip", r"d:\tmp\Python3")
>>> rst
\'d:\\tmp\\twofiles.zip\'
>>>
shutil.unpack_archive()
- 功能:解包操作
- 格式:
shutil.unpack_archive(\'归档文件地址\', \'解包之后的地址\')
- 返回值:无
>>> rst = shutil.unpack_archive(r"d:\tmp\twofiles.zip", r"d:\tmp\Python")
>>> rst
>>>
zipfile
>>> import zipfile # 下面的例子就不重复这个导入操作了
>>>
压缩
- 用算法把多个文件或者文件夹无损或者有损合并到一个文件当中
zipfile.ZipFile()
- 功能:创建一个
ZipFile 对象,表示一个 zip 文件
- 格式:
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
-
file: 文件的路径或类文件对象
-
mode: 打开 zip 文件的模式
-
r 默认值,读已经存在的 zip 文件
-
w 新建一个 zip 文档或覆盖一个已经存在的 zip 文档
-
a 将数据附加到一个现存的 zip 文档中
-
compression: 在写 zip 文档时使用的压缩方法,它的值可以是
zipfile.ZIP_STORED
zipfile.ZIP_DEFLATED
- 如果要操作的
zip 文件大小超过 2G,应该将 allowZip64 设置为 True
>>> zf = zipfile.ZipFile(r"d:\tmp\twofiles.zip")
>>>
ZipFile.getinfo()
- 功能:获取
zip 文档内指定文件的信息
- 格式:
ZipFile.getinfo(name)
- 返回值:一个
zipfile.ZipInfo 对象,它包括文件的详细信息
>>> rst = zf.getinfo("text.txt")
>>> rst
<ZipInfo filename=\'text.txt\' compress_type=deflate filemode=\'-rw-rw-rw-\' file_size=0 compress_size=2>
>>>
ZipFile.namelist()
>>> zf.namelist()
[\'text.py\', \'text.txt\']
>>>
- 功能:解压
zip 文档中的所有文件到当前目录
- 格式:
ZipFile.extractall([path[, members[, pwd]]])
-
members 的默认值为 zip 文档内的所有文件名称列表,可以自己设置,选择要解压的文件
>>> rst = zf.extractall(r"d:\tmp\twofiles") # twofiles 可以改为任意合法的名字
>>> rst
>>>
- 结果
-
d 盘下,tmp 文件夹中,多出了一个名为 twofiles 的文件夹
-
twofiles.zip 中的文件已解压至 twofiles 文件夹