[英]How to copy a file in a zipfile into a certain directory?
I need only one subfile in each of 500 zipfiles, the paths are the same, like: 我只需要500个zipfiles中的一个子文件,路径是相同的,如:
120132.zip/A/B/C/target_file
212332.zip/A/B/C/target_file
....
How can I copy all these target files into one directory? 如何将所有这些目标文件复制到一个目录中? Keeping the entire paths in the new directory will be the best, which I mean is:
保持新目录中的整个路径是最好的,我的意思是:
target_dir/
120132/A/B/C/target_file
212332/A/B/C/target_file
......
I tried it with Python modules zipfile and shutil 我用Python模块zipfile和shutil试了一下
However, copyfile from shutil takes the entire path as argument but when I tried to directly copy the target file it will raise filenotfind error. 但是,来自shutil的 copyfile将整个路径作为参数,但是当我尝试直接复制目标文件时,会引发filenotfind错误。 When unzipped by the zipfile.Zipfile, the target file will be accessible but copyfile becomes invalid.
当zipfile.Zip文件解压缩时,目标文件将可访问,但copyfile变为无效。
How can I do this correctly and efficiently ? 我该如何正确有效地完成这项工作?
ZipFile.extract
accepts optional path
specifying into which directory it will extract file: ZipFile.extract
接受可选path
指定它将提取文件的目录:
import os
import zipfile
zip_filepath = ['120132.zip', '212332.zip', ...] # or glob.glob('...zip')
target_dir = '/path/to/target_dir'
for path in zip_filepath:
with zipfile.ZipFile(path) as zf:
dirname = os.path.join(
target_dir, os.path.splitext(os.path.basename(path))[0]
)
zf.extract('A/B/C/target_file', path=dirname)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.