简体   繁体   中英

How to extract zip file in different directory in python?

I'm writing a python (2.7) script that extracts files from a zip file with an encrypted password. For this, I'm using the ZipFile module to extract files in a different directory. I have followed all the answer whatever is mentioned on here. How to extract all the files from the zip file into a different directory?

I have tried to extract all files into different directories but result is: it is creating directory inside the targeted directory.

 try:
    with ZipFile(os.path.join(app.config['UPLOAD_FOLDER'], filename)) as zf:             
        zf.extractall('/Users/dipak.das/desktop/docs/',None,b'12345')
 except RuntimeError as e:
    print e

I expected the output of the above script should extract all files inside path directories.But my code is creating a directory inside docs directories "/Users/dipak.das/desktop/docs/" and extracting all files.

Assuming that you want the files extracted with no subdirectories...

Totally untested but perhaps try something like

import os, shutil

destdir = '/Users/dipak.das/desktop/docs/'
with ZipFile(os.path.join(app.config['UPLOAD_FOLDER'], filename)) as zf:
  for name in zf.namelist():
    source = zf.open(name, 'r', b'12345')
    destpath = os.path.join(destdir, os.path.basename(name))
    target = open(destpath, 'w')
    shutil.copyfileobj(source, target)
    target.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM