Using Python's zipfile module

1 to determine whether the zip file

#!/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)))
zipfile_is_zipfile.py

running result 

[root@ mnt]# python3 zipfile_is_zipfile.py 
  tcp_server.py  False
        test.py  False
       test.zip  True

 2, see the inside of zip file name

#!/usr/bin/env python3
# encoding: utf-8

import zipfile

with zipfile.ZipFile('test.zip', 'r') as zf:
    print(zf.namelist())
zipfile_namelist.py

running result

[root@ mnt]# python3 zipfile_namelist.py 
['tcp_client.py', 'tcp_server.py', 'test.py']

 3, the size of the view inside the zip file, the file name, modification time and other parameters

#!/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')
zipfile_infolist.py

 running result

[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, specify a file name to view zip files inside information

#!/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 ( ' File name: File Size {}: {} bytes ' .format (filename, info.file_size))
zipfile_getinfo.py

 running result

[root @ mnt] # python3 zipfile_getinfo.py 
File name: test.py File size: 426 bytes 
file: README.txt, there is no zip inside

 5. Check inside the zip file contents

#!/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( ' File name: File Content {}: {} ' .format (filename, Data))
zipfile_read.py

 running result

[root @ mnt] # python3 zipfile_read.py 
File name: test.py file contents: b " # / usr / bin / env python3 \ r \ the n-! " 
file: README.txt, there is no zip inside

6, increasing the zip file compression

#!/usr/bin/env python3
# encoding: utf-8

import zipfile

with zipfile.ZipFile('write.zip','w') as zf:
    print('增加test.py压缩')
    zf.write('test.py')
zipfile_write.py

 running result

[root @ mnt] # python3 zipfile_write.py 
increase test.py compressed 

[the root @ mnt] # LL
 -rw-R & lt - r-- . 1 the root the root   278 Jan 10  . 11 : 37 [  Write . ZIP 
-rw-R & lt - R & lt - . 1 the root the root   160. Jan 10  . 11 : 37 [ zipfile_write.py

7, set the compression mode compressed files

#!/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 ( ' increase test.py file compression and compression mode settings ' , MODE_NAME) 
    wf.write ( ' test.py ' , compress_type = compression)
zipfile_write_compression.py

running result

[root @ mnt] # python3 zipfile_write_compression.py 
creating an archive 
increase test.py file compressed and the compression mode setting DEFLATED 

[the root @ mnt] # LL
 -rw-R & lt - r-- . 1 the root the root   256 Jan 10  14 : . 11 write_compression . ZIP 
-rw-R & lt - r-- . 1 the root the root   542 Jan 10  14 : . 11 zipfile_write_compression.py

8, compressed files, and modify the compressed file name

#!/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')
zipfile_write_arcname.py 

running result

[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, get data from memory, compressed into a zip file

#!/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'))
zipfile_writestr.py

running result

[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, compressed data, the compressed file and sets time parameters

#!/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)
zipfile_writestr_zipinfo.py

 running result

[root @ mnt] # python3 zipfile_writestr_info.py 

[root @ mnt] # the unzip the -l writestr_zipinfo.zip 
Archive: writestr_zipinfo.zip 
  the Length a Date Time the Name
 --------- ---------- ---- ----- 
       33 01-10-2020 14:36    from_string.txt 
which is compressed Notes
 --------- ------- 
       33 1 File

11, to compress the file, continue to increase the sample file compression

# / Usr / bin / env python3! 
# Encoding: UTF-8 

Import the ZipFile 

Print ( ' create a compressed ZIP ' ) 
with zipfile.ZipFile ( ' append.zip ' , ' w ' ) AS zf: 
    zf.write ( ' the Test. Py ' ) 

Print ( ' to add a new document file append.zip ' ) 
with zipfile.ZipFile ( ' append.zip ' , ' a ' ) AS AF: 
    af.write ( ' the test.py ' , the arcname =' New_test.py ' ) 

Print ( ' increase the compressed file complete ' )
zipfile_append.py

running result

[root @ mnt] # python3 zipfile_append.py 
create a compressed zip 
to append.zip file to add new files 
to increase the compressed file finishes 

[root @ mnt] # the unzip the -l append.zip 
Archive: append.zip 
  the Length a Date Time the Name
 --- ------ ---------- ----- ---- 
      166 01-10-2020 11:35    test.py
       166 01-10-2020 11:35    new_test.py
 - ------- -------- 
      332 2 Files

 12, all inside view compressed files directory and file name

#!/usr/bin/env python3
# encoding: utf-8

import zipfile

with zipfile.ZipFile('example.zip', 'r') as rf:
    print(rf.printdir())
zipfile_printdir.py

 

running result

[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, using zipfile module, the pyc py codes and compressed into a zip file

#!/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)
zipfile_pyzipfile.py

running result

[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

Guess you like

Origin www.cnblogs.com/ygbh/p/12174677.html