- How to: Compress and extract files
- Example 1: Create and extract a .zip file
- Example 2: Extract specific file extensions
- Example 3: Add a file to an existing zip
- Example 4: Compress and decompress .gz files
- Extracting zip file contents to specific directory in Python 2.7
- 6 Answers 6
- Zip File. Extract ToDirectory Метод
- Определение
- Перегрузки
- ExtractToDirectory(String, String)
- Параметры
- Исключения
- Примеры
- Комментарии
- Применяется к
- ExtractToDirectory(String, String, Boolean)
- Параметры
- Исключения
- Комментарии
- Применяется к
- ExtractToDirectory(String, String, Encoding)
- Параметры
- Исключения
- Комментарии
How to: Compress and extract files
The System.IO.Compression namespace contains the following types for compressing and decompressing files and streams. You can also use these types to read and modify the contents of a compressed file.
The following examples show some of the operations you can perform with compressed files. These examples require the following NuGet packages to be added to your project:
If you’re using .NET Framework, add references to these two libraries to your project:
Example 1: Create and extract a .zip file
The following example shows how to create and extract a compressed .zip file by using the ZipFile class. The example compresses the contents of a folder into a new .zip file, and then extracts the zip to a new folder.
To run the sample, create a start folder in your program folder and populate it with files to zip.
Example 2: Extract specific file extensions
The next example iterates through the contents of an existing .zip file and extracts files that have a .txt extension. It uses the ZipArchive class to access the zip, and the ZipArchiveEntry class to inspect the individual entries. The extension method ExtractToFile for the ZipArchiveEntry object is available in the System.IO.Compression.ZipFileExtensions class.
To run the sample, place a .zip file called result.zip in your program folder. When prompted, provide a folder name to extract to.
When unzipping files, you must look for malicious file paths, which can escape out of the directory you unzip into. This is known as a path traversal attack. The following example demonstrates how to check for malicious file paths and provides a safe way to unzip.
Example 3: Add a file to an existing zip
The following example uses the ZipArchive class to access an existing .zip file, and adds a file to it. The new file gets compressed when you add it to the existing zip.
Example 4: Compress and decompress .gz files
You can also use the GZipStream and DeflateStream classes to compress and decompress data. They use the same compression algorithm. You can decompress GZipStream objects that are written to a .gz file by using many common tools. The following example shows how to compress and decompress a directory of files by using the GZipStream class:
Extracting zip file contents to specific directory in Python 2.7
This is the code I am currently using to extract a zip file that lives in the same current working directory as the script. How can I specify a different directory to extract to?
The code I tried is not extracting it where I want.
6 Answers 6
I think you’ve just got a mixup here. Should probably be something like the following:
and if you just want to extract all the files:
Use pip install zipfile36 for recent versions of Python
I tried the other answers in this thread, but the final solution for me was simply:
Look at extractall, but use it only with trustworthy zip files.
Adding to secretmike’s answer above with support for python 2.6 for extracting all files.
If you just want to extract a zip file from the command line using Python (say because you don’t have the unzip command available), then you can call the zipfile module directly
Take a look at the docs. It also supports compression and listing the contents.
Peter de Rivaz has a point in the comment above. You are going to want to have the directory in the call to open(). You are going to want to do something like this:
I’ve modified the code to ask the user input the file name and its path where it need to be extracted and so the user will’ve more control on where to put the extracted folder and what name should be assigned to the extracted folder.
Zip File. Extract ToDirectory Метод
Определение
Извлекает все файлы в указанном ZIP-архиве в каталогу в файловой системе. Extracts all the files in the specified zip archive to a directory on the file system.
Перегрузки
Извлекает все файлы в указанном ZIP-архиве в каталогу в файловой системе. Extracts all the files in the specified zip archive to a directory on the file system.
Извлекает все файлы в указанном архиве в каталоге в файловой системе. Extracts all of the files in the specified archive to a directory on the file system.
Извлекает все файлы в указанном ZIP-архиве к каталог в файловой системе и использует указанную кодировку для имен записей. Extracts all the files in the specified zip archive to a directory on the file system and uses the specified character encoding for entry names.
Извлекает все файлы в указанном архиве в каталоге в файловой системе. Extracts all of the files in the specified archive to a directory on the file system.
ExtractToDirectory(String, String)
Извлекает все файлы в указанном ZIP-архиве в каталогу в файловой системе. Extracts all the files in the specified zip archive to a directory on the file system.
Параметры
Путь к архиву, который требуется извлечь. The path to the archive that is to be extracted.
Путь к каталогу, в котором следует поместить извлеченные файлы, заданный как относительный или абсолютный путь. The path to the directory in which to place the extracted files, specified as a relative or absolute path. Относительный путь интерпретируется относительно текущего рабочего каталога. A relative path is interpreted as relative to the current working directory.
Исключения
Параметр destinationDirectoryName или sourceArchiveFileName является Empty, содержит только пробелы или хотя бы один недопустимый символ. destinationDirectoryName or sourceArchiveFileName is Empty, contains only white space, or contains at least one invalid character.
Параметр destinationDirectoryName или sourceArchiveFileName имеет значение null . destinationDirectoryName or sourceArchiveFileName is null .
Указанная длина пути в destinationDirectoryName или sourceArchiveFileName превышает максимальную длину, определенную в системе. The specified path in destinationDirectoryName or sourceArchiveFileName exceeds the system-defined maximum length.
Указанный путь недопустим (например, он соответствует неподключенному диску). The specified path is invalid (for example, it is on an unmapped drive).
Каталог, заданный параметром destinationDirectoryName , уже существует. The directory specified by destinationDirectoryName already exists.
-или- -or- Имя записи в архиве имеет значение Empty, содержит только пробелы или содержит по крайней мере один недопустимый символ. The name of an entry in the archive is Empty, contains only white space, or contains at least one invalid character.
-или- -or- Извлечение записи архива создаст файл, который находится вне каталога, заданного destinationDirectoryName . Extracting an archive entry would create a file that is outside the directory specified by destinationDirectoryName . (Например, это может произойти, если имя записи содержит методы доступа родительского каталога.) (For example, this might happen if the entry name contains parent directory accessors.) -или- -or- Запись архива, которую требуется извлечь, имеет то же имя, что и запись, которая уже была извлекается из того же архива. An archive entry to extract has the same name as an entry that has already been extracted from the same archive.
Вызывающий код не имеет необходимого разрешения на доступ к архиву или целевому каталогу. The caller does not have the required permission to access the archive or the destination directory.
destinationDirectoryName или sourceArchiveFileName содержит недопустимый формат. destinationDirectoryName or sourceArchiveFileName contains an invalid format.
Не удалось найти sourceArchiveFileName . sourceArchiveFileName was not found.
Архив, заданный параметром sourceArchiveFileName , не является допустимым ZIP-архивом. The archive specified by sourceArchiveFileName is not a valid zip archive.
-или- -or- Не удалось найти запись архива или она была повреждена. An archive entry was not found or was corrupt.
-или- -or- Запись архива была сжата с помощью неподдерживаемого метода сжатия. An archive entry was compressed by using a compression method that is not supported.
Примеры
В этом примере показано, как создать и извлечь ZIP-архив с помощью ZipFile класса. This example shows how to create and extract a zip archive by using the ZipFile class. Она сжимает содержимое папки в ZIP-архив и извлекает это содержимое в новую папку. It compresses the contents of a folder into a zip archive and extracts that content to a new folder. Чтобы использовать класс ZipFile, укажите в проекте ссылку на сборку System.IO.Compression.FileSystem . To use the ZipFile class, you must reference the System.IO.Compression.FileSystem assembly in your project.
Комментарии
Этот метод создает указанный каталог и все подкаталоги. This method creates the specified directory and all subdirectories. Каталог назначения не может уже существовать. The destination directory cannot already exist. Исключения, связанные с проверкой путей в destinationDirectoryName sourceArchiveFileName параметрах или, вызываются перед извлечением. Exceptions related to validating the paths in the destinationDirectoryName or sourceArchiveFileName parameters are thrown before extraction. В противном случае, если во время извлечения возникает ошибка, архив остается частично извлеченным. Otherwise, if an error occurs during extraction, the archive remains partially extracted. Каждый извлеченный файл имеет тот же относительный путь к каталогу, который указан в destinationDirectoryName качестве исходной записи в корневую папку архива. Each extracted file has the same relative path to the directory specified by destinationDirectoryName as its source entry has to the root of the archive.
Применяется к
ExtractToDirectory(String, String, Boolean)
Извлекает все файлы в указанном архиве в каталоге в файловой системе. Extracts all of the files in the specified archive to a directory on the file system.
Параметры
Путь в файловой системе к архиву, который требуется извлечь. The path on the file system to the archive that is to be extracted.
Путь к целевому каталогу в файловой системе. The path to the destination directory on the file system. Указанный каталог не должен существовать, но каталог, в котором он находится, должен существовать. The directory specified must not exist, but the directory that it is contained in must exist.
Значение true для перезаписи файлов; в противном случае — значение false . true to overwrite files; false otherwise.
Исключения
sourceArchiveFileName или destinationDirectoryName представляет собой строку нулевой длины, содержащую только пробелы или один или несколько недопустимых символов, заданных методом InvalidPathChars. sourceArchiveFileName or destinationDirectoryName is a zero-length string, contains only whitespace, or contains one or more invalid characters as defined by InvalidPathChars.
Параметр sourceArchiveFileName или destinationDirectoryName имеет значение null . sourceArchiveFileName or destinationDirectoryName is null .
sourceArchiveFileName или destinationDirectoryName указывает путь, имя файла или оба параметра, которые превышают установленное в системе максимальное значение. sourceArchiveFileName or destinationDirectoryName specifies a path, a file name, or both that exceed the system-defined maximum length.
Путь, указанный sourceArchiveFileName или destinationDirectoryName , является недопустимым (например, он ведет на несопоставленный диск). The path specified by sourceArchiveFileName or destinationDirectoryName is invalid (for example, it is on an unmapped drive).
Каталог, заданный параметром destinationDirectoryName , уже существует. The directory specified by destinationDirectoryName already exists.
Произошла ошибка ввода-вывода. An I/O error has occurred.
Имя ZipArchiveEntry имеет нулевую длину, содержит только пробелы или один или несколько недопустимых символов, заданных методом InvalidPathChars. The name of a ZipArchiveEntry is zero-length, contains only whitespace, or contains one or more invalid characters as defined by InvalidPathChars.
Извлечение ZipArchiveEntry может привести к назначению файла, находящегося за пределами целевого каталога (например, из-за наличия методов доступа к родительскому каталогу). Extracting a ZipArchiveEntry would result in a file destination that is outside the destination directory (for example, because of parent directory accessors).
ZipArchiveEntry имеет то же имя, что и уже извлеченная запись из того же архива. A ZipArchiveEntry has the same name as an already extracted entry from the same archive.
У вызывающего объекта отсутствует необходимое разрешение. The caller does not have the required permission.
Параметр sourceArchiveFileName или destinationDirectoryName имеет недопустимый формат. sourceArchiveFileName or destinationDirectoryName is in an invalid format.
Не удалось найти sourceArchiveFileName . sourceArchiveFileName was not found.
Архив, заданный параметром sourceArchiveFileName , не является допустимым ZipArchive. The archive specified by sourceArchiveFileName is not a valid ZipArchive.
ZipArchiveEntry поврежден или не может быть найден. A ZipArchiveEntry was not found or was corrupt.
ZipArchiveEntry сжат с помощью неподдерживаемого метода сжатия. A ZipArchiveEntry has been compressed using a compression method that is not supported.
Комментарии
Указанный каталог не должен существовать. The specified directory must not exist. Метод создает указанный каталог и все подкаталоги. The method creates the specified directory and all subdirectories.
Если при извлечении архива возникла ошибка, архив будет извлечен частично. If there is an error while extracting the archive, the archive will remain partially extracted.
Каждая запись будет извлечена таким образом, что извлеченный файл имеет тот же относительный путь к тому, destinationDirectoryName что и запись в архив. Each entry will be extracted such that the extracted file has the same relative path to the destinationDirectoryName as the entry has to the archive.
Путь может указывать сведения относительного или абсолютного пути. The path can specify relative or absolute path information. Относительный путь интерпретируется относительно текущего рабочего каталога. A relative path is interpreted as relative to the current working directory.
Если файл для архивации имеет неверное время последнего изменения, то будет использоваться первая дата и время, представленные в формате метки времени ZIP (полночь 1 января 1980). If a file to be archived has an invalid last modified time, the first date and time representable in the Zip timestamp format (midnight on January 1, 1980) will be used.
Применяется к
ExtractToDirectory(String, String, Encoding)
Извлекает все файлы в указанном ZIP-архиве к каталог в файловой системе и использует указанную кодировку для имен записей. Extracts all the files in the specified zip archive to a directory on the file system and uses the specified character encoding for entry names.
Параметры
Путь к архиву, который требуется извлечь. The path to the archive that is to be extracted.
Путь к каталогу, в котором следует поместить извлеченные файлы, заданный как относительный или абсолютный путь. The path to the directory in which to place the extracted files, specified as a relative or absolute path. Относительный путь интерпретируется относительно текущего рабочего каталога. A relative path is interpreted as relative to the current working directory.
Кодирование, используемое при чтении или записи имен записей в этом архиве. The encoding to use when reading or writing entry names in this archive. Задайте значение для этого параметра, только если кодирование требуется для взаимодействия с инструментами и библиотеками ZIP-архива, которые не поддерживают кодирование UTF-8 для имен записей. Specify a value for this parameter only when an encoding is required for interoperability with zip archive tools and libraries that do not support UTF-8 encoding for entry names.
Исключения
Параметр destinationDirectoryName или sourceArchiveFileName является Empty, содержит только пробелы или хотя бы один недопустимый символ. destinationDirectoryName or sourceArchiveFileName is Empty, contains only white space, or contains at least one invalid character.
-или- -or- entryNameEncoding установлено на кодировку Юникода, отличное от UTF-8. entryNameEncoding is set to a Unicode encoding other than UTF-8.
Параметр destinationDirectoryName или sourceArchiveFileName имеет значение null . destinationDirectoryName or sourceArchiveFileName is null .
Указанная длина пути в destinationDirectoryName или sourceArchiveFileName превышает максимальную длину, определенную в системе. The specified path in destinationDirectoryName or sourceArchiveFileName exceeds the system-defined maximum length.
Указанный путь недопустим (например, он соответствует неподключенному диску). The specified path is invalid (for example, it is on an unmapped drive).
Каталог, заданный параметром destinationDirectoryName , уже существует. The directory specified by destinationDirectoryName already exists.
-или- -or- Имя записи в архиве имеет значение Empty, содержит только пробелы или содержит по крайней мере один недопустимый символ. The name of an entry in the archive is Empty, contains only white space, or contains at least one invalid character.
-или- -or- Извлечение записи архива создаст файл, который находится вне каталога, заданного destinationDirectoryName . Extracting an archive entry would create a file that is outside the directory specified by destinationDirectoryName . (Например, это может произойти, если имя записи содержит методы доступа родительского каталога.) (For example, this might happen if the entry name contains parent directory accessors.) -или- -or- Запись архива, которую требуется извлечь, имеет то же имя, что и запись, которая уже была извлекается из того же архива. An archive entry to extract has the same name as an entry that has already been extracted from the same archive.
Вызывающий код не имеет необходимого разрешения на доступ к архиву или целевому каталогу. The caller does not have the required permission to access the archive or the destination directory.
destinationDirectoryName или sourceArchiveFileName содержит недопустимый формат. destinationDirectoryName or sourceArchiveFileName contains an invalid format.
Не удалось найти sourceArchiveFileName . sourceArchiveFileName was not found.
Архив, заданный параметром sourceArchiveFileName , не является допустимым ZIP-архивом. The archive specified by sourceArchiveFileName is not a valid zip archive.
-или- -or- Не удалось найти запись архива или она была повреждена. An archive entry was not found or was corrupt.
-или- -or- Запись архива была сжата с помощью неподдерживаемого метода сжатия. An archive entry was compressed by using a compression method that is not supported.
Комментарии
Этот метод создает указанный каталог и все подкаталоги. This method creates the specified directory and all subdirectories. Каталог назначения не может уже существовать. The destination directory cannot already exist. Исключения, связанные с проверкой путей в destinationDirectoryName sourceArchiveFileName параметрах или, вызываются перед извлечением. Exceptions related to validating the paths in the destinationDirectoryName or sourceArchiveFileName parameters are thrown before extraction. В противном случае, если во время извлечения возникает ошибка, архив остается частично извлеченным. Otherwise, if an error occurs during extraction, the archive remains partially extracted. Каждый извлеченный файл имеет тот же относительный путь к каталогу, который указан в destinationDirectoryName качестве исходной записи в корневую папку архива. Each extracted file has the same relative path to the directory specified by destinationDirectoryName as its source entry has to the root of the archive.
Если для параметра задано entryNameEncoding значение, отличное от null , имена записей декодированы в соответствии со следующими правилами. If entryNameEncoding is set to a value other than null , entry names are decoded according to the following rules:
Для имен записей, в которых не задан флаг кодировки языка (в битовом флаге общего назначения локального заголовка файла), имена записей декодированы с использованием указанной кодировки. For entry names where the language encoding flag (in the general-purpose bit flag of the local file header) is not set, the entry names are decoded by using the specified encoding.
Для записей, в которых установлен флаг кодировки языка, имена записей декодированы с помощью UTF-8. For entries where the language encoding flag is set, the entry names are decoded by using UTF-8.
Если параметр entryNameEncoding имеет значение null , имена записей декодированы в соответствии со следующими правилами. If entryNameEncoding is set to null , entry names are decoded according to the following rules:
Для записей, в которых не задан флаг кодировки языка (в битовом флаге общего назначения локального заголовка файла), имена записей декодированы с использованием текущей системной кодовой страницы по умолчанию. For entries where the language encoding flag (in the general-purpose bit flag of the local file header) is not set, entry names are decoded by using the current system default code page.
Для записей, в которых установлен флаг кодировки языка, имена записей декодированы с помощью UTF-8. For entries where the language encoding flag is set, the entry names are decoded by using UTF-8.