How to copy a file in a zipfile into a certain directory?

Question:

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 ?

Asked By: Spike

||

Answers:

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)
Answered By: falsetru

i maybe be late to the party…

If i have luck, and you remember.
What was your solution?
I have this excact problem.

Answered By: mthomassen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.