How to use python unzip?
In Python, unzipping refers to extracting compressed files into a specified directory or memory. Python offers various methods for decompressing files, with the most commonly used being the zipfile module.
Here is the basic usage of the zipfile module for decompression:
- import the zipfile module:
import zipfile
- Open the compressed file:
with zipfile.ZipFile('example.zip', 'r') as zip_ref:
# 这里的example.zip是要解压的压缩文件名或路径,'r'表示以只读方式打开
- Extract files to a specified directory:
zip_ref.extractall('destination_folder')
# 这里的destination_folder是要解压到的目录名或路径
- Extracting a single file:
zip_ref.extract('file.txt', 'destination_folder')
# 这里的file.txt是要解压的文件名,'destination_folder'是要解压到的目录名或路径
Here is the complete sample code:
import zipfile
with zipfile.ZipFile('example.zip', 'r') as zip_ref:
zip_ref.extractall('destination_folder')
The above code will extract the example.zip file into the destination_folder directory.
Caution: When decompressing files, make sure the compressed file exists and that the specified directory or path is valid.