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 ?


Answer: [`ZipFile.extract`](https://docs.python.org/3/library/zipfile.html#zipfile.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)
    

