简体   繁体   中英

Python cannot open absolute path in zipfile.ZipFile

I'm trying to parse through a group of zips in a directory other than the cwd (and then read a csv file inside of it - I'm not concerned with that here), with the following code:

for name in glob.glob('/Users/brendanmurphy/Documents/chicago-data/16980*.zip'):
    base = os.path.basename(name)
    filename = os.path.splitext(base)[0]

    datadirectory = '/Users/brendanmurphy/Documents/chicago-data/'
    fullpath = ''.join([datadirectory, base])
    csv_file = '.'.join([filename, 'csv'])
    ozid, start, end = filename.split("-")
    zfile = zipfile.ZipFile(fullpath)

But trying to pass the full path to zipfile.ZipFile gives the following full traceback:

File "Chicago_csv_reader.py", line 33, in <module>
    zfile = zipfile.ZipFile(fullpath)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/zipfile.py", line 766, in __init__
self._RealGetContents()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/zipfile.py", line 807, in _RealGetContents
raise BadZipfile, "File is not a zip file"
zipfile.BadZipfile: File is not a zip file

What is the correct way to pass the path of a zip file not in the cwd to the ZipFile handler?

You aren't joining your path and base name properly.

Do not do

filename = os.path.splitext(base)[0]

You are stripping the .zip extension from your file, which means you are pointing somewhere else.

Try generating fullpath like so:

# Use your "base" string, not your "filename" string!
fullpath = os.path.join(datadirectory, base)

Then for sanity check before you try to unzip the file:

if not os.path.exists(fullpath):
    raise Exception("Path '{0}' does not exist!".format(fullpath))
zfile = zipfile.ZipFile(fullpath)

You've got a couple of problems. First, 'name' is already the zipfile name, you don't need to do anything to it. Second, ''.join([datadirectory, base]) just appends the two names and omits the path separator. This should work:

datadirectory = '/Users/brendanmurphy/Documents/chicago-data/'
for name in glob.glob('/Users/brendanmurphy/Documents/chicago-data/16980*.zip'):
    filename = os.path.splitext(base)[0]
    csv_file = os.path.join(datadirectory, filename + '.csv')
    ozid, start, end = filename.split("-")
    zfile = zipfile.ZipFile(name)

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