简体   繁体   中英

Extracting zip files using python

I'm trying to get all zip files in a specific directory name "downloaded" and to extract all of their content to a directory named "extracted".

I don't know why, after I'm iterating only existing files name, I get an error that there is no such file...

allFilesList = os.listdir(os.getcwd()+"/downloaded")
print allFilesList #verify - correct expected list
from zipfile import ZipFile
os.chdir(os.getcwd()+"/extracted/")
print os.getcwd() #verify - correct expected dir

for fileName in allFilesList: 
    print fileName
    with ZipFile(fileName, 'r') as zipFileObject:
        if os.path.exists(fileName):
            print "Skipping extracting " + fileName
            continue
        zipFileObject.extractall(pwd='hello')                   
        print "Saving extracted file to extracted/",fileName
print "all files has been successfully extracted"

Error message:

File "program.py", line 77, in <module>
with ZipFile(fileName, 'r') as zipFileObject:
File "/usr/lib/python2.7/zipfile.py", line 779, in __init__
    self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'zipFile1.zip'

You're getting the list of filenames from one directory, then changing to another, and trying to extract the files from that directory that likely don't exist:

allFilesList = os.listdir(os.getcwd()+"/downloaded")
# ...
os.chdir(os.getcwd()+"/extracted/")
# ...
    with ZipFile(fileName, 'r') as zipFileObject:

If you change that file ZipFile command to something like this:

    with ZipFile(os.path.join("..", "downloaded", fileName), 'r') as zipFileObject:

You should be able to open the file in the directory you found it in.

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