为了从zip提取所有.txt文件,您需要遍历zipfile中的所有文件,检查文件是否为txt文件。如果它是txt文件,则将其解压缩。为此,我们将使用zipfile模块及其提取功能。
import zipfile my_zip = zipfile.Zipfile('my_zip_file.zip') # Specify your zip file's name here storage_path = '.' for file in my_zip.namelist(): if my_zip.getinfo(file).filename.endswith('.txt'): my_zip.extract(file, storage_path) # extract the file to current folder if it is a text file
运行上面的代码将打开my_zip_file.zip并从中提取所有txt文件,并将它们存储在当前目录中。