Python et les fichiers zip ************************** Il existe dans python le module **zipfile** pour gérer les fichiers zip test de fichier zip ------------------- .. code-block:: python import zipfile for filename in [ 'README.txt', 'example.zip', 'bad_example.zip', 'notthere.zip' ]: print '%20s %s' % (filename, zipfile.is_zipfile(filename)) :: $ python zipfile_is_zipfile.py README.txt False example.zip True bad_example.zip False notthere.zip False lecture des méta-data --------------------- .. code-block:: python import zipfile zf = zipfile.ZipFile('example.zip', 'r') print zf.namelist() :: $ python zipfile_namelist.py ['README.txt'] ou .. code-block:: python import datetime import zipfile def print_info(archive_name): zf = zipfile.ZipFile(archive_name) for info in zf.infolist(): print info.filename print '\tComment:\t', info.comment print '\tModified:\t', datetime.datetime(*info.date_time) print '\tSystem:\t\t', info.create_system, '(0 = Windows, 3 = Unix)' print '\tZIP version:\t', info.create_version print '\tCompressed:\t', info.compress_size, 'bytes' print '\tUncompressed:\t', info.file_size, 'bytes' print if __name__ == '__main__': print_info('example.zip') extraire une archive zip ------------------------ .. code-block:: python import zipfile zf = zipfile.ZipFile('example.zip') for filename in [ 'README.txt', 'notthere.txt' ]: try: data = zf.read(filename) except KeyError: print 'ERROR: Did not find %s in zip file' % filename else: print filename, ':' print repr(data) print :: $ python zipfile_read.py README.txt : 'The examples for the zipfile module use this file and example.zip as data.\n' ERROR: Did not find notthere.txt in zip file Pour extraire une archive complète .. code-block:: python with zipfile.ZipFile("myfile.zip", "r") as z: z.extractall("my_dir") créer une archive zip --------------------- .. code-block:: python from zipfile_infolist import print_info import zipfile print 'creating archive' zf = zipfile.ZipFile('zipfile_write.zip', mode='w') try: print 'adding README.txt' zf.write('README.txt') finally: print 'closing' zf.close() print print_info('zipfile_write.zip') :: $ python zipfile_write.py creating archive adding README.txt closing README.txt Comment: Modified: 2007-12-16 10:08:50 System: 3 (0 = Windows, 3 = Unix) ZIP version: 20 Compressed: 75 bytes Uncompressed: 75 bytes ou plus simple .. code-block:: python myzip = zipfile.ZipFile('test.zip', 'w', zipfile.ZIP_DEFLATED) myzip.write(xls_file) myzip.close()