Python之zipfile模块的使用
1、判断是否是zip文件
#!/usr/bin/env python3 # encoding: utf-8 import zipfile filenames = ['tcp_server.py', 'test.py', 'test.zip'] for filename in filenames: print('{:>15} {}'.format(filename, zipfile.is_zipfile(filename)))
运行效果
[root@ mnt]# python3 zipfile_is_zipfile.py tcp_server.py False test.py False test.zip True
2、查看zip里面的文件名
#!/usr/bin/env python3 # encoding: utf-8 import zipfile with zipfile.ZipFile('test.zip', 'r') as zf: print(zf.namelist())
运行效果
[root@ mnt]# python3 zipfile_namelist.py ['tcp_client.py', 'tcp_server.py', 'test.py']
3、查看zip里面文件的大小、文件名、修改时间等参数
#!/usr/bin/env python3 # encoding: utf-8 import zipfile import datetime def print_info(archive_name): with zipfile.ZipFile(archive_name) as zf: for info in zf.infolist(): print(info.filename) print(' Comment :', info.comment) mod_date = datetime.datetime(*info.date_time) print(' Modified :', mod_date) if info.create_system == 0: system = 'Windows' elif info.create_system == 3: system = 'Unix' else: system = 'UNKNOWN' print(' System :', system) print(' Zip Version :', info.create_version) print(' Compressed :', info.compress_size, 'bytes') print(' UnCompressed :', info.file_size, 'bytes') if __name__ == '__main__': print_info('test.zip')
运行效果
[root@ mnt]# python3 zipfile_infolist.py tcp_client.py Comment : b'' Modified : 2020-01-09 18:01:58 System : Windows Zip Version : 63 Compressed : 221 bytes UnCompressed : 301 bytes tcp_server.py Comment : b'' Modified : 2020-01-09 18:15:06 System : Windows Zip Version : 63 Compressed : 511 bytes UnCompressed : 996 bytes test.py Comment : b'' Modified : 2020-01-09 16:58:52 System : Windows Zip Version : 63 Compressed : 206 bytes UnCompressed : 426 bytes
4、指定文件名查看zip里面的文件信息
#!/usr/bin/env python3 # encoding: utf-8 import zipfile with zipfile.ZipFile('test.zip') as zf: filenames = ['test.py', 'README.txt'] for filename in filenames: try: info = zf.getinfo(filename) except KeyError: print('文件:{},不存在zip里面'.format(filename)) else: print('文件名:{} 文件大小:{} bytes'.format(filename, info.file_size))
运行效果
[root@ mnt]# python3 zipfile_getinfo.py 文件名:test.py 文件大小:426 bytes 文件:README.txt,不存在zip里面
5、查看zip里面文件的内容
#!/usr/bin/env python3 # encoding: utf-8 import zipfile with zipfile.ZipFile('test.zip') as zf: filenames = ['test.py', 'README.txt'] for filename in filenames: try: data = zf.read(filename) except KeyError: print('文件:{},不存在zip里面'.format(filename)) else: print('文件名:{} 文件内容:{}'.format(filename, data))
运行效果
[root@ mnt]# python3 zipfile_read.py 文件名:test.py 文件内容:b"#!/usr/bin/env python3\r\n" 文件:README.txt,不存在zip里面
6、增加文件zip压缩
#!/usr/bin/env python3 # encoding: utf-8 import zipfile with zipfile.ZipFile('write.zip','w') as zf: print('增加test.py压缩') zf.write('test.py')
运行效果
[root@ mnt]# python3 zipfile_write.py 增加test.py压缩 [root@ mnt]# ll -rw-r--r-- 1 root root 278 Jan 10 11:37 write.zip -rw-r--r-- 1 root root 160 Jan 10 11:37 zipfile_write.py
7、设置压缩模式压缩文件
#!/usr/bin/env python3 # encoding: utf-8 import zipfile try: import zlib compression = zipfile.ZIP_DEFLATED except (ImportError, AttributeError): compression = zipfile.ZIP_STORED modes = { # set集合 zipfile.ZIP_DEFLATED: 'deflated', zipfile.ZIP_STORED: 'stored', } print('创建压缩文件') with zipfile.ZipFile('write_compression.zip', 'w') as wf: mode_name = modes[compression] print('增加 test.py 文件压缩并且设置压缩模式', mode_name) wf.write('test.py', compress_type=compression)
运行效果
[root@ mnt]# python3 zipfile_write_compression.py 创建压缩文件 增加 test.py 文件压缩并且设置压缩模式 deflated [root@ mnt]# ll -rw-r--r-- 1 root root 256 Jan 10 14:11 write_compression.zip -rw-r--r-- 1 root root 542 Jan 10 14:11 zipfile_write_compression.py
8、压缩文件,并且修改被压缩的文件名
#!/usr/bin/env python3 # encoding: utf-8 import zipfile with zipfile.ZipFile('write_artcname.zip', 'w') as wf: wf.write('test.py',arcname='artcle_name_test.py')
运行效果
[root@ mnt]# python3 zipfile_write_arcname.py [root@ mnt]# ll -rw-r--r-- 1 root root 302 Jan 10 14:17 write_artcname.zip -rw-r--r-- 1 root root 167 Jan 10 14:16 zipfile_write_arcname.py [root@ mnt]# unzip -l write_artcname.zip Archive: write_artcname.zip Length Date Time Name --------- ---------- ----- ---- 166 01-10-2020 11:35 artcle_name_test.py --------- ------- 166 1 file
9、从内存中获取数据,压缩为zip文件
#!/usr/bin/env python3 # encoding: utf-8 import zipfile msg = 'This Data did not exist in a file' with zipfile.ZipFile('writestr.zip', 'w', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr('from_string.txt', msg) with zipfile.ZipFile('writestr.zip', 'r') as zf: print(zf.read('from_string.txt'))
运行效果
[root@ mnt]# python3 zipfile_writestr.py b'This Data did not exist in a file' [root@ mnt]# ll -rw-r--r-- 1 root root 163 Jan 10 14:25 writestr.zip -rw-r--r-- 1 root root 312 Jan 10 14:25 zipfile_writestr.py
10、压缩数据,并且设置被压缩文件的时间等参数
#!/usr/bin/env python3 # encoding: utf-8 import zipfile import time msg = 'This Data did not exist in a file' with zipfile.ZipFile('writestr_zipinfo.zip', 'w') as zf: info = zipfile.ZipInfo('from_string.txt', date_time=time.localtime(time.time())) info.compress_type = zipfile.ZIP_DEFLATED info.comment = '这是压缩的注释'.encode('utf-8') info.create_system = 0 zf.writestr(info, msg)
运行效果
[root@ mnt]# python3 zipfile_writestr_info.py [root@ mnt]# unzip -l writestr_zipinfo.zip Archive: writestr_zipinfo.zip Length Date Time Name --------- ---------- ----- ---- 33 01-10-2020 14:36 from_string.txt 这是压缩的注释 --------- ------- 33 1 file
11、往压缩文件,增加文件继续压缩的示例
#!/usr/bin/env python3 # encoding: utf-8 import zipfile print('创建压缩zip') with zipfile.ZipFile('append.zip', 'w') as zf: zf.write('test.py') print('往append.zip文件增加新的文件') with zipfile.ZipFile('append.zip', 'a') as af: af.write('test.py', arcname='new_test.py') print('增加压缩文件完成')
运行效果
[root@ mnt]# python3 zipfile_append.py 创建压缩zip 往append.zip文件增加新的文件 增加压缩文件完成 [root@ mnt]# unzip -l append.zip Archive: append.zip Length Date Time Name --------- ---------- ----- ---- 166 01-10-2020 11:35 test.py 166 01-10-2020 11:35 new_test.py --------- ------- 332 2 files
12、查看压缩文件里面所有的目录和文件名
#!/usr/bin/env python3 # encoding: utf-8 import zipfile with zipfile.ZipFile('example.zip', 'r') as rf: print(rf.printdir())
运行效果
[root@ mnt]# python3 zipfile_printdir.py File Name Modified Size add/ 2020-01-10 14:45:36 0 add/test.zip 2020-01-10 09:58:18 1362 add/write_artcname.zip 2020-01-10 14:17:44 302 add/writestr.zip 2020-01-10 14:25:22 163 content_update.txt 2020-01-09 11:53:32 336
13、利用zipfile模块,把py代码转为pyc并且压缩打包成zip文件
#!/usr/bin/env python3 # encoding: utf-8 import zipfile if __name__ == '__main__': with zipfile.PyZipFile('pyzipfile.zip', 'w') as wf: wf.debug = 3 print('增加Python多个文件') wf.writepy('.') for name in wf.namelist(): print(name)
运行效果
[root@ mnt]# python3 zipfile_pyzipfile.py 增加Python多个文件 Adding files from directory . Adding test.pyc Adding zipfile_pyzipfile.pyc test.pyc zipfile_pyzipfile.pyc [root@ mnt]# unzip -l pyzipfile.zip Archive: pyzipfile.zip Length Date Time Name --------- ---------- ----- ---- 233 01-10-2020 14:57 test.pyc 349 01-10-2020 14:57 zipfile_pyzipfile.pyc --------- ------- 582 2 files