|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
利用zipfile 模块中的函数,Python 程序可以创建和打开(或解压)ZIP 文件。下面具体介绍一下:
class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
创建一个ZipFile对象,表示一个zip文件。
参数file表示文件的路径或类文件对象(file-like object)
参数mode指示打开zip文件的模式,默认值为’r’,表示读已经存在的zip文件
也可以为’w’或’a’,’w’表示新建一个zip文档或覆盖一个已经存在的zip文档,’a’表示将数据附加到一个现存的zip文档中。
参数compression表示在写zip文档时使用的压缩方法,它的值可以是zipfile. ZIP_STORED 或zipfile. ZIP_DEFLATED。
如果要操作的zip文件大小超过2G,应该将allowZip64设置为True。
打开ZipFile后记得调用ZipFile.close()关闭zip文件,养成良好习惯!
ZipFile还提供了如下常用的方法和属性:
ZipFile.getinfo(name):
获取zip文档内指定文件的信息。返回一个zipfile.ZipInfo对象,它包括文件的详细信息。将在下面具体介绍该对象。
ZipFile.infolist()
获取zip文档内所有文件的信息,返回一个zipfile.ZipInfo的列表。
ZipFile.namelist()
获取zip文档内所有文件的名称列表。
ZipFile.extract(member[, path[, pwd]])
将zip文档内的指定文件解压到当前目录。参数member指定要解压的文件名称或对应的ZipInfo对象
参数path指定了解析文件保存的文件夹;参数pwd为解压密码。
ZipFile.extractall([path[, members[, pwd]]])
解压zip文档中的所有文件到当前目录。参数members的默认值为zip文档内的所有文件名称列表,也可以自己设置,选择要解压的文件名称。
ZipFile.printdir()
将zip文档内的信息打印到控制台上。
ZipFile.setpassword(pwd)
设置zip文档的密码。
ipFile.read(name[, pwd])
获取zip文档内指定文件的二进制数据。
ZipFile.write(filename[, arcname[, compress_type]])
将指定文件添加到zip文档中。filename为文件路径,arcname为添加到zip文档之后保存的名称。
参数compress_type表示压缩方法,它的值可以是zipfile. ZIP_STORED 或zipfile. ZIP_DEFLATED。
ZipFile.writestr(zinfo_or_arcname, bytes)
writestr()支持将二进制数据直接写入到压缩文档。
Class ZipInfo
ZipFile.getinfo(name) 方法返回的是一个ZipInfo对象,表示zip文档中相应文件的信息。它支持如下属性:
ZipInfo.filename: 获取文件名称。
ZipInfo.date_time: 获取文件最后修改时间。返回一个包含6个元素的元组:(年, 月, 日, 时, 分, 秒)
ZipInfo.compress_type: 压缩类型。
ZipInfo.comment: 文档说明。
ZipInfo.extr: 扩展项数据。
ZipInfo.create_system: 获取创建该zip文档的系统。
ZipInfo.create_version: 获取 创建zip文档的PKZIP版本。
ZipInfo.extract_version: 获取 解压zip文档所需的PKZIP版本。
ZipInfo.reserved: 预留字段,当前实现总是返回0。
ZipInfo.flag_bits: zip标志位。
ZipInfo.volume: 文件头的卷标。
ZipInfo.internal_attr: 内部属性。
ZipInfo.external_attr: 外部属性。
ZipInfo.header_offset: 文件头偏移位。
ZipInfo.CRC: 未压缩文件的CRC-32。
ZipInfo.compress_size: 获取压缩后的大小。
ZipInfo.file_size: 获取未压缩的文件大小。
接下来,举几个例子说明一下
1)读取ZIP 文件
---------------------------------------------------------------------------------------------
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.namelist()
['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']
>>> spamInfo = exampleZip.getinfo('spam.txt')
>>> spamInfo.file_size
13908
>>> spamInfo.compress_size
3828
---------------------------------------------------------------------------------------------
说明:
ZipFile 对象有一个namelist()方法,返回ZIP 文件中包含的所有文件和文件夹的字符串的列表。
这些字符串可以传递给ZipFile 对象的getinfo()方法,返回一个关于特定文件的ZipInfo 对象。
ZipInfo 对象有自己的属性,诸如表示字节数的file_size和compress_size,它们分别表示原来文件大小和压缩后文件大小。
ZipFile 对象表示整个归档文件,而ZipInfo 对象则保存该归档文件中每个文件的有用信息。
2)从ZIP 文件中解压缩
ZipFile 对象的extractall()方法从ZIP 文件中解压缩所有文件和文件夹,放到当前工作目录中。
当然填入参数后,亦可解压到指定目录中,如前所述。
---------------------------------------------------------------------------------------------
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.extractall()
>>> exampleZip.close()
---------------------------------------------------------------------------------------------
ZipFile 对象的extract()方法从ZIP 文件中解压缩单个文件。
---------------------------------------------------------------------------------------------
>>> exampleZip.extract('spam.txt')
'C:\\spam.txt'
>>> exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')
'C:\\some\\new\\folders\\spam.txt'
>>> exampleZip.close()
---------------------------------------------------------------------------------------------
3)创建和添加到ZIP 文件
---------------------------------------------------------------------------------------------
>>> import zipfile
>>> newZip = zipfile.ZipFile('new.zip', 'w')
>>> newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)
>>> newZip.close()
---------------------------------------------------------------------------------------------
这段代码将创建一个新的ZIP 文件,名为new.zip,它包含spam.txt 压缩后的内容。
要记住,就像写入文件一样,写模式将擦除ZIP 文件中所有原有的内容。
如果只是希望将文件添加到原有的ZIP 文件中,就要向zipfile.ZipFile()传入'a'作为第二个参数,以添加模式打开ZIP 文件。
4)将一个文件夹备份到一个ZIP 文件(综合)
---------------------------------------------------------------------------------------------
# Copies an entire folder and its contents into
# a zip file whose filename increments.
import zipfile, os
def backupToZip(folder):
# Backup the entire contents of "folder" into a zip file.
folder = os.path.abspath(folder) # make sure folder is absolute
# Figure out the filename this code should used based on
# what files already exist.
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
# Create the zip file.
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
# Walk the entire folder tree and compress the files in each folder.
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
# Add the current folder to the ZIP file.
Fdname = os.path.relpath('.\\', '..\\')
# Add all the files in this folder to the path named the name of this folder and add the files to the ZIP file.
for filename in filenames:
if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
continue # don't backup the backup ZIP files
backupName = os.path.relpath(os.path.join(foldername, filename))
backupZip.write(backupName, Fdname + '\\' + backupName)
backupZip.close()
print('Done.')
backupToZip(os.getcwd())
--------------------------------------------------------------------------------------------- |
|