zipfile
zipfile.ZipFile
zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None)
复制代码file: 生成压缩文件所在的路径
mode: r, w, a, x
compression: ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA
compresslevel: When using ZIP_STORED or ZIP_LZMA it has no effect.
When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information).
Zipfile.write
ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None)
复制代码filename: 即将被压缩的文件路径
arcname: 归档文件路径
If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry
Note Archive names should be relative to the archive root, that is, they should not start with a path separator.
Note If arcname (or filename, if arcname is not given) contains a null byte, the name of the file in the archive will be truncated at the null byte.
code
场景:将source目录中的所有文件打包压缩命名为compress_complete.zip并放入target目录下
project
│
└───source
│ └── file1.md
│ └── file2.md
│ └── file3.md
└───target
└── compress_complete.zip
复制代码import os
import zipfile
source_dir = '/project/source' (pwd查看绝对路径替换)
zipname = '/project/target/compress_complete.zip' (pwd查看绝对路径替换)
startdir = source_dir # 要压缩的文件夹路径
file_news = zipname # 压缩后文件夹的名字
z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED) # 参数一:文件夹名
for dirpath, dirnames, filenames in os.walk(startdir):
fpath = dirpath.replace(startdir, '')
fpath = fpath and fpath + os.sep or ''
for filename in filenames:
z.write(os.path.join(dirpath, filename), fpath+filename)
print ('压缩成功')
z.close()
复制代码