How to decompress files in Python?
You can utilize the zipfile module in Python to unzip files. Here is a basic example code:
import zipfile
def unzip_file(zip_file, extract_dir):
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
zip_ref.extractall(extract_dir)
# 指定要解压缩的压缩文件和解压缩目录
zip_file = 'example.zip'
extract_dir = 'extracted_files'
# 调用解压缩函数
unzip_file(zip_file, extract_dir)
In the example above, we imported the zipfile module and defined a function called unzip_file that takes two parameters: the compressed file to be uncompressed and the directory to extract it to. We then used the zipfile.ZipFile method to open the compressed file and used the extractall method to decompress the files into the specified directory.
Before running the code above, it is necessary to place the compressed file to be decompressed (e.g. example.zip) in the same directory as the code, or access the file by specifying the full path. The decompressed file will be saved in the specified extraction directory (e.g. extracted_files).