Reputation: 329
I need only one subfile in each of 500 zipfiles, the paths are the same, like:
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
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. When unzipped by the zipfile.Zipfile, the target file will be accessible but copyfile becomes invalid.
How can I do this correctly and efficiently ?
Upvotes: 2
Views: 10043
Reputation: 369424
ZipFile.extract
accepts optional path
specifying into which directory it will extract file:
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)
Upvotes: 7