如何解决使用python将目录中的压缩文件夹中的所有文件提取到没有文件夹的其他目录中
# importing required modules
from zipfile import ZipFile
# specifying the zip file name
file_name = "C:\\OPR\\109521P.zip"
# opening the zip file in READ mode
with ZipFile(file_name,'r') as zip:
# printing all the contents of the zip file
result =zip.printdir()
# extracting all the files
print('Extracting all the files now...')
zip.extractall('images')
print('Done!')
我在一个压缩文件夹的一个子文件夹中压缩了大约10张图像,现在我想将所有图像直接提取到没有该子文件夹的其他目录中,我尝试使用os.path.basename(name),但是我出现严重错误。
上面的代码之后,我将所有图像保存在一个文件夹中,
C:\ images \ 109521P
上面是提取所有10张图像的输出位置,现在我希望直接在这些位置提取图像
C:\ images
所以我想省略子文件夹109521P,并希望在上述位置直接提取图像。
解决方法
my_dir = r"C:\OPR"
my_zip = r"C:\OPR\109521P.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)
我得到了答案,只是发布了