从zip中提取文件,而不使用python ZipFile保留结构? [英] Extract files from zip without keeping the structure using python ZipFile?
问题描述
我尝试从一个文件夹中包含子文件夹的.zip中提取所有文件.我希望子文件夹中的所有文件都仅提取到一个文件夹中而不保留原始结构.此刻,我解压缩所有文件,将文件移动到文件夹,然后删除以前的子文件夹.具有相同名称的文件将被覆盖.
I try to extract all files from .zip containing subfolders in one folder. I want all the files from subfolders extract in only one folder without keeping the original structure. At the moment, I extract all, move the files to a folder, then remove previous subfolders. The files with same names are overwrited.
是否可以在写入文件之前完成?
Is it possible to do it before writing files?
这里是一个结构,例如:
Here is a structure for example:
my_zip/file1.txt
my_zip/dir1/file2.txt
my_zip/dir1/dir2/file3.txt
my_zip/dir3/file4.txt
最后我希望这个:
my_dir/file1.txt
my_dir/file2.txt
my_dir/file3.txt
my_dir/file4.txt
我可以在此代码中添加什么?
What can I add to this code ?
import zipfile
my_dir = "D:\\Download\\"
my_zip = "D:\\Download\\my_file.zip"
zip_file = zipfile.ZipFile(my_zip, 'r')
for files in zip_file.namelist():
zip_file.extract(files, my_dir)
zip_file.close()
如果我从zip_file.namelist()重命名文件路径,则出现此错误:
if I rename files path from zip_file.namelist(), I have this error:
KeyError: "There is no item named 'file2.txt' in the archive"
推荐答案
这将打开zip存档成员的文件句柄,提取文件名并将其复制到目标文件中(这就是ZipFile.extract
的工作方式,而无需照顾子目录).
This opens file handles of members of the zip archive, extracts the filename and copies it to a target file (that's how ZipFile.extract
works, without taken care of subdirectories).
import os
import shutil
import zipfile
my_dir = r"D:\Download"
my_zip = r"D:\Download\my_file.zip"
with zipfile.ZipFile(my_zip) as zip_file:
for member in zip_file.namelist():
filename = os.path.basename(member)
# skip directories
if not filename:
continue
# copy file (taken from zipfile's extract)
source = zip_file.open(member)
target = open(os.path.join(my_dir, filename), "wb")
with source, target:
shutil.copyfileobj(source, target)
这篇关于从zip中提取文件,而不使用python ZipFile保留结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!