12.4. zipfile — Work with ZIP archives

Novo na versão 1.6.

Código Fonte: Lib/zipfile.py


O formato de arquivo ZIP é um padrão de compactação e arquivamento. Este módulo fornece ferramentas para criar, ler, escrever, adicionar, e listar um arquivo ZIP. Qualquer uso avançado deste módulo vai exigir um entendimento do formato, como definido em PKZIP Application Note.

This module does not currently handle multi-disk ZIP files. It can handle ZIP files that use the ZIP64 extensions (that is ZIP files that are more than 4 GByte in size). It supports decryption of encrypted files in ZIP archives, but it currently cannot create an encrypted file. Decryption is extremely slow as it is implemented in native Python rather than C.

Este módulo define os seguintes itens:

exception zipfile.BadZipfile

The error raised for bad ZIP files (old name: zipfile.error).

exception zipfile.LargeZipFile

Este erro ocorre quando um arquivo ZIP precisa da funcionalidade ZIP64 que não está habilitada.

class zipfile.ZipFile

A classe para ler e escrever arquivos ZIP. Veja a seçã Objetos ZipFile para detalhes do construtor.

class zipfile.PyZipFile

Classe para criar arquivos ZIP contendo bibliotecas Python.

class zipfile.ZipInfo([filename[, date_time]])

Classe usada para representar informação sobre um membro de um archive. Instâncias desta classe são retornadas pelos métodos getinfo() e infolist() de objetos da classe ZipFile. A maioria dos usuários do módulo zipfile não vai precisar criar, mas apenas usar objetos criados pelo módulo. filename deveria ser o caminho completo do membro do arquivo, e date_time deveria ser uma tupla contendo seis campos que descrevem o momento da última modificação no arquivo; os campos são descritos na seção ZipInfo Objects.

zipfile.is_zipfile(filename)

Retorna True se filename é um arquivo ZIP válido baseado no seu magic number, caso contrário retorna False. filename pode ser um arquivo ou um file-like também.

Alterado na versão 2.7: Suporte para arquivo e objetos file-like.

zipfile.ZIP_STORED

Constante numérica para um membro de um arquivo descompactado

zipfile.ZIP_DEFLATED

The numeric constant for the usual ZIP compression method. This requires the zlib module. No other compression methods are currently supported.

Ver também

PKZIP Application Note

Documentação do formato de arquivo ZIP feita por Phil Katz, criador do formato e dos algoritmos usados.

Info-ZIP Home Page

Informações sobre o programas de arquivamento e desenvolvimento de bibliotecas do projeto Info-ZIP

12.4.1. Objetos ZipFile

class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])

Open a ZIP file, where file can be either a path to a file (a string) or a file-like object. The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, or 'a' to append to an existing file. If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it. If file does not refer to a ZIP file, then a new ZIP archive is appended to the file. This is meant for adding a ZIP archive to another file (such as python.exe).

Alterado na versão 2.6: If mode is a and the file does not exist at all, it is created.

compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED or ZIP_DEFLATED; unrecognized values will cause RuntimeError to be raised. If ZIP_DEFLATED is specified but the zlib module is not available, RuntimeError is also raised. The default is ZIP_STORED. If allowZip64 is True zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 2 GB. If it is false (the default) zipfile will raise an exception when the ZIP file would require ZIP64 extensions. ZIP64 extensions are disabled by default because the default zip and unzip commands on Unix (the InfoZIP utilities) don’t support these extensions.

Alterado na versão 2.7.1: If the file is created with mode 'a' or 'w' and then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file.

ZipFile is also a context manager and therefore supports the with statement. In the example, myzip is closed after the with statement’s suite is finished—even if an exception occurs:

with ZipFile('spam.zip', 'w') as myzip:
    myzip.write('eggs.txt')

Novo na versão 2.7: Adicionado o uso de ZipFile como um gerenciador de contexto.

ZipFile.close()

Fecha o arquivo. Você deve chamar close() antes de sair do seu programa ou registros essenciais não serão gravados.

ZipFile.getinfo(name)

Retorna um objeto ZipInfo com informações sobre o name do membro do arquivo. Chamar getinfo() para um nome não encontrado no arquivo lança um KeyError.

ZipFile.infolist()

Retorna uma lista contendo um objeto ZipInfo para cada membro do arquivo. Os objetos estão na mesma ordem das entradas no arquivo ZIP em disco se um arquivo existente foi aberto.

ZipFile.namelist()

Retorna uma lista de membros do arquivo por nome.

ZipFile.open(name[, mode[, pwd]])

Extract a member from the archive as a file-like object (ZipExtFile). name is the name of the file in the archive, or a ZipInfo object. The mode parameter, if included, must be one of the following: 'r' (the default), 'U', or 'rU'. Choosing 'U' or 'rU' will enable universal newline support in the read-only object. pwd is the password used for encrypted files. Calling open() on a closed ZipFile will raise a RuntimeError.

Nota

The file-like object is read-only and provides the following methods: read(), readline(), readlines(), __iter__(), next().

Nota

If the ZipFile was created by passing in a file-like object as the first argument to the constructor, then the object returned by open() shares the ZipFile’s file pointer. Under these circumstances, the object returned by open() should not be used after any additional operations are performed on the ZipFile object. If the ZipFile was created by passing in a string (the filename) as the first argument to the constructor, then open() will create a new file object that will be held by the ZipExtFile, allowing it to operate independently of the ZipFile.

Nota

Os métodos open(), read() e extract() podem receber um nome de arquivo ou um objeto ZipInfo. Voce vai gostar disso quando tentar ler um arquivo ZIP que contém membros com nomes duplicados.

Novo na versão 2.6.

ZipFile.extract(member[, path[, pwd]])

Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object). Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a ZipInfo object. pwd is the password used for encrypted files.

Retorna o caminho normalizado criado (um diretório ou novo arquivo).

Novo na versão 2.6.

Nota

Se um nome de arquivo membro é um caminho absoluto, o drive/UNC e barras no início serão removidos, por exemplo: ///foo/bar se torna foo/bar no Unix, e C:\foo\bar vira foo\bar no Windows. E todos os componentes ".." no nome de um arquivo membro serão removidos, por exemplo: ../../foo../../ba..r vira foo../ba..r. No Windows caracteres ilegais (:, <, >, |, ", ?, and *) são substituídos por underscore (_).

ZipFile.extractall([path[, members[, pwd]]])

Extrai todos os membros de um arquivo para o diretório atual. path especifica um diretório diferente para gravar os arquivos extraídos. members é opcional e deve ser um sub-conjunto da lista retornada por namelist(). pwd é uma senha usada para criptografar arquivos.

Aviso

Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of path, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..".

Alterado na versão 2.7.4: The zipfile module attempts to prevent that. See extract() note.

Novo na versão 2.6.

ZipFile.printdir()

Imprime a tabela de conteúdos de um arquivo para sys.stdout.

ZipFile.setpassword(pwd)

Seta pwd como senha padrão para extrair arquivos criptografados.

Novo na versão 2.6.

ZipFile.read(name[, pwd])

Return the bytes of the file name in the archive. name is the name of the file in the archive, or a ZipInfo object. The archive must be open for read or append. pwd is the password used for encrypted files and, if specified, it will override the default password set with setpassword(). Calling read() on a closed ZipFile will raise a RuntimeError.

Alterado na versão 2.6: pwd was added, and name can now be a ZipInfo object.

ZipFile.testzip()

Read all the files in the archive and check their CRC’s and file headers. Return the name of the first bad file, or else return None. Calling testzip() on a closed ZipFile will raise a RuntimeError.

ZipFile.write(filename[, arcname[, compress_type]])

Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. The archive must be open with mode 'w' or 'a' – calling write() on a ZipFile created with mode 'r' will raise a RuntimeError. Calling write() on a closed ZipFile will raise a RuntimeError.

Nota

There is no official file name encoding for ZIP files. If you have unicode file names, you must convert them to byte strings in your desired encoding before passing them to write(). WinZip interprets all file names as encoded in CP437, also known as DOS Latin.

Nota

Nomes de arquivo compactado devem ser relativos a raiz do mesmo, isto é, não devem começar com um separador de caminho.

Nota

Se arcname (ou filename, se arcname não for informado) contém um byte nulo, o nome do arquivo no arquivo compactado será truncado no byte nulo.

ZipFile.writestr(zinfo_or_arcname, bytes[, compress_type])

Write the string bytes to the archive; zinfo_or_arcname is either the file name it will be given in the archive, or a ZipInfo instance. If it’s an instance, at least the filename, date, and time must be given. If it’s a name, the date and time is set to the current date and time. The archive must be opened with mode 'w' or 'a' – calling writestr() on a ZipFile created with mode 'r' will raise a RuntimeError. Calling writestr() on a closed ZipFile will raise a RuntimeError.

If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry, or in the zinfo_or_arcname (if that is a ZipInfo instance).

Nota

Quando é passada uma instância de ZipInfo ou o parâmetro zinfo_or_arcname, o método de compactação usado será aquele especificado no compress_type do objeto ZipInfo. Por padrão, o construtor da classe ZipInfo seta este membro para ZIP_STORED.

Alterado na versão 2.7: O argumento compress_type.

Os seguintes atributos de dados também estão disponíveis:

ZipFile.debug

O nível de saída de debug para usar. Pode ser setado de 0` (valor padrão, sem nenhuma saída) a 3 (com mais saída). A informação de debug é escrita em sys.stdout.

ZipFile.comment

The comment text associated with the ZIP file. If assigning a comment to a ZipFile instance created with mode ‘a’ or ‘w’, this should be a string no longer than 65535 bytes. Comments longer than this will be truncated in the written archive when close() is called.

12.4.2. Objetos PyZipFile

The PyZipFile constructor takes the same parameters as the ZipFile constructor. Instances have one method in addition to those of ZipFile objects.

PyZipFile.writepy(pathname[, basename])

Search for files *.py and add the corresponding file to the archive. The corresponding file is a *.pyo file if available, else a *.pyc file, compiling if necessary. If the pathname is a file, the filename must end with .py, and just the (corresponding *.py[co]) file is added at the top level (no path information). If the pathname is a file that does not end with .py, a RuntimeError will be raised. If it is a directory, and the directory is not a package directory, then all the files *.py[co] are added at the top level. If the directory is a package directory, then all *.py[co] are added under the package name as a file path, and if any subdirectories are package directories, all of these are added recursively. basename is intended for internal use only. The writepy() method makes archives with file names like this:

string.pyc                                # Top level name
test/__init__.pyc                         # Package directory
test/test_support.pyc                          # Module test.test_support
test/bogus/__init__.pyc                   # Subpackage directory
test/bogus/myfile.pyc                     # Submodule test.bogus.myfile

12.4.3. ZipInfo Objects

Instances of the ZipInfo class are returned by the getinfo() and infolist() methods of ZipFile objects. Each object stores information about a single member of the ZIP archive.

Instances have the following attributes:

ZipInfo.filename

Name of the file in the archive.

ZipInfo.date_time

The time and date of the last modification to the archive member. This is a tuple of six values:

Index

Valor

0

Year (>= 1980)

1

Month (one-based)

2

Day of month (one-based)

3

Hours (zero-based)

4

Minutes (zero-based)

5

Seconds (zero-based)

Nota

The ZIP file format does not support timestamps before 1980.

ZipInfo.compress_type

Type of compression for the archive member.

ZipInfo.comment

Comment for the individual archive member.

ZipInfo.extra

Expansion field data. The PKZIP Application Note contains some comments on the internal structure of the data contained in this string.

ZipInfo.create_system

System which created ZIP archive.

ZipInfo.create_version

PKZIP version which created ZIP archive.

ZipInfo.extract_version

PKZIP version needed to extract archive.

ZipInfo.reserved

Must be zero.

ZipInfo.flag_bits

ZIP flag bits.

ZipInfo.volume

Volume number of file header.

ZipInfo.internal_attr

Internal attributes.

ZipInfo.external_attr

External file attributes.

ZipInfo.header_offset

Byte offset to the file header.

ZipInfo.CRC

CRC-32 of the uncompressed file.

ZipInfo.compress_size

Size of the compressed data.

ZipInfo.file_size

Size of the uncompressed file.

12.4.4. Interface de Linha de Comando

The zipfile module provides a simple command-line interface to interact with ZIP archives.

If you want to create a new ZIP archive, specify its name after the -c option and then list the filename(s) that should be included:

$ python -m zipfile -c monty.zip spam.txt eggs.txt

Passing a directory is also acceptable:

$ python -m zipfile -c monty.zip life-of-brian_1979/

If you want to extract a ZIP archive into the specified directory, use the -e option:

$ python -m zipfile -e monty.zip target-dir/

For a list of the files in a ZIP archive, use the -l option:

$ python -m zipfile -l monty.zip

12.4.4.1. Opções de linha de comando

-l <zipfile>

List files in a zipfile.

-c <zipfile> <source1> ... <sourceN>

Create zipfile from source files.

-e <zipfile> <output_dir>

Extract zipfile into target directory.

-t <zipfile>

Test whether the zipfile is valid or not.