Unzip files with python

Распаковка файлов из архивов zip или tar.gz с помощью Python

cat box1

Из этой статьи вы узнаете, как распаковать один или несколько архивов zip и tar.gz и получить информацию о них средствами языка Python. Мы рассмотрим извлечение одного или нескольких файлов из архива.

Шаг 1: получить информацию из архива zip или tar.gz

Сперва мы просмотрим содержимое zip-файла с помощью этого фрагмента кода:

from zipfile import ZipFile zipfile = 'file.zip' z = ZipFile(zipfile) z.infolist()

Таким образом мы сможем узнать размеры и имена двух файлов:

Шаг 2: перечислить и прочитать все файлы из архива

Теперь мы можем получить список всех файлов в архиве:

from zipfile import ZipFile archive = 'file.zip' zip_file = ZipFile(archive) [text_file.filename for text_file in zip_file.infolist() ]
['pandas-dataframe-background-color-based-condition-value-python.png', 'text1.txt']

Если вам нужно отсортировать файлы – например, получить только json – или прочитать их в формате датафреймов Pandas, можно сделать это следующим образом:

from zipfile import ZipFile archive = 'file.zip' zip_file = ZipFile(archive) dfs = dfs

Шаг 3: извлечь файлы из zip-архива

Пакет zipfile можно использовать для извлечения файлов из zip-архивов. Базовый пример:

import zipfile archive = 'file.zip' with zipfile.ZipFile(archive, 'r') as zip_file: zip_file.extractall(directory_to_extract_to)

Шаг 4: извлечь файлы из tar/tar.gz

Чтобы извлечь файлы из архивов tar/tar.gz , можно воспользоваться кодом, приведенным ниже. Он использует модуль tarfile и разделяет эти два типа, чтобы применить подходящий режим распаковки:

import tarfile zipfile = 'file.zip' if zipfile.endswith("tar.gz"): tar = tarfile.open(zipfile, "r:gz") elif zipfile.endswith("tar"): tar = tarfile.open(zipfile, "r:") tar.extractall() tar.close()

Примечание: все файлы из архива будут распакованы в текущей для данного скрипта рабочей директории.

Шаг 5: извлечь один файл из архива

Если вам нужно получить только один файл из архива, можно использовать метод zipObject.extract(fileName, ‘temp_py’) . Простой пример:

import zipfile archive = 'file.zip' with zipfile.ZipFile(archive, 'r') as zip_file: zip_file.extract('text1.txt', '.')

В этом примере мы извлечём файл ‘text1.txt’ в текущую рабочую директорию. Если вам нужно извлечь файл в другую директорию, можете изменить второй параметр — ‘.’

Заключение

В этом уроке мы выяснили, как с помощью Python извлечь один или несколько файлов из различных архивов, а также — как вывести список запакованных файлов и получить из них информацию. Мы затронули работу с двумя пакетами: zipfile и tarfile.

Источник

How to Unzip Files in Python

Compressed files take up less space, which makes them easier to transfer over the internet or store on your hard drive. However, they need to be unzipped or extracted before they can be utilized. For instance, if you have a large dataset in a zipped file format, you need to extract it to a folder in order to access its contents.

In this article, we will explore different approaches to unzipping files in Python.

How to Unzip Files in Python?

To unzip files in Python, apply the following approaches:

Method 1: Unzip Files in Python Using “zipfile” Module

The “zip” file can be extracted using the “zipfile” module in Python. This module uses the “extractall()” method to extract all the files from a zip file to a specified directory. The “extract()” method, however, extracts a single file or a list of files from a zip file to a specified directory.

The original path and the name of the “zip” file that needs to be extracted throughout the blog are shown in the below snippet:

Example 1: Extract All the Files From a Zip File Using the “zipfile extractall()” Method

Let’s overview the following example code:

import zipfile
with zipfile.ZipFile ( r «C:\Users\p\Documents\program\sample.zip» , «r» ) as zip:
zip.extractall ( r «C:\Users\p\Documents\program» )

In the above code, the “zipfile.ZipFile()” function is used to open the zip file, and the “zip.extractall()” method extracts all the files from the specified zip file.

The above outcome implies that all the files from a zip file have been extracted.

Example 2: Extract a Single File From a Zip File Via the “zipfile extract()” Method

The below code is used to extract a single file from the zip file:

import zipfile
with zipfile.ZipFile ( r «C:\Users\p\Documents\program\sample.zip» , «r» ) as zip:
zip.extract ( «example.py» , r «C:\Users\p\Documents\program» )

In the above code, the “zipfile.ZipFile()” function is used to open the zip file, and the “zip.extract()” method is applied to extract the specific file from the given zip file.

Based on the above output, the single file from the zip file is extracted.

Method 2: Unzip Files in Python Using the “shutil” Module

Another way to unzip files in Python is via the “shutil” module. This module provides a higher-level interface for working with files and directories. The “unpack_archive()” method of the “shutil” module is used to extract an archive file to a specified directory. This method supports various archive formats, such as “zip”, “tar”, “gz”, etc.

Go through the below-stated code snippet:

import shutil
shutil.unpack_archive ( r «C:\Users\p\Documents\program\sample.zip» , r «C:\Users\p\Documents\program» , ‘zip’ )

According to the above lines of code, the “shutil.unpack_archive()” method takes the zip file’s complete path and the target directory as its arguments, respectively, and unzips the files accordingly.

Based on the above output, both files have been extracted to the specified path appropriately.

Conclusion

The “zipfile” module and the “shutil” module are used to unzip single or multiple files from the specified zip file in Python. The “extractall()” method and “extract()” method of the “zipfile” module are used to unzip the single or all the files of the given zip file, respectively. The “unpack_archive()” method of the “shutil” module is used to extract an archive file to a specified directory. This post presented various ways to unzip the specified zip file using numerous examples.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.

Источник

Читайте также:  Php number format online
Оцените статью