从zip fi内的目录提取

2024-10-06 08:38:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我现有的代码(一个部分)在这篇文章的底部被借用。在

我想做的是从zip文件的内的一个目录中提取所有文件。不是zip文件的全部内容,而是zip中目录(/theme_files/)中的文件。我已经引进了必要的图书馆。在

将文件从[filename].tpk/theme_files提取到./workspace/[output]/

.tpk=.zip

theme_zip = zipfile.ZipFile(current_dir + "/themes/" + theme_name + ".tpk", 'r')
theme_zip.extractall(output_dir)
theme_zip.close()

Tags: 文件代码目录output图书馆dirfileszip
3条回答
for item in (f for f in theme_zip.filelist if 'theme_files/' in f.filename):
    theme_zip.extract(item, output_dir)

您可以使用^{}并使用对从^{}返回的文件名的列表理解来设置path和{}参数:

import zipfile 

output_dir = './workspace/[output]/'
file = current_dir + "/themes/" + theme_name + ".tpk"

with zipfile.ZipFile(file, 'r') as f:
    files = [n for n in f.namelist() 
                   if n.startswith('/theme_files/') and not n.endswith('/')]
    f.extractall(path=output_dir , members=files)

使用regex搜索特定子文件夹中的文件名。+逐个文件提取它们:

with open('<file-name>.zip', 'rb') as f:
    zf = zipfile.ZipFile(f)
    for file in [m.group() for m in (re.search(r'/theme/(.+)', file) for file in file_list) if m]:
        zf.extract(file)

相关问题 更多 >