What is the method for reading compressed files in Python?
In Python, the typical method for reading compressed files is to use relevant libraries to extract the files before reading the contents. Commonly used libraries include zipfile and tarfile.
- compressed file containing multiple files
import zipfile
with zipfile.ZipFile('example.zip', 'r') as zip_file:
for file_name in zip_file.namelist():
with zip_file.open(file_name) as file:
content = file.read()
# 处理文件内容
- compressed file containing multiple files
import tarfile
with tarfile.open('example.tar', 'r') as tar_file:
for file in tar_file.getmembers():
f = tar_file.extractfile(file)
content = f.read()
# 处理文件内容
The code above demonstrates how to open a compressed file and read its contents. The appropriate library and method can be chosen based on the specific situation.