Python无法在zipfile.ZipFile中打开绝对路径
我正在尝试处理一个目录中的多个压缩文件(zip文件),这个目录不在当前工作目录(cwd)下,然后读取里面的一个csv文件(这里我不想讨论这个)。我用的代码是:
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)
但是,当我尝试把压缩文件的完整路径传给zipfile.ZipFile时,出现了以下的错误信息:
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
那么,正确的方法是什么,才能把不在当前工作目录下的压缩文件路径传给ZipFile处理器呢?
2 个回答
0
你没有正确地把路径和文件名连接起来。
不要这样做:
filename = os.path.splitext(base)[0]
你把文件的 .zip
后缀去掉了,这样就指向了其他地方。
试着这样生成 fullpath
:
# Use your "base" string, not your "filename" string!
fullpath = os.path.join(datadirectory, base)
然后在你尝试解压文件之前,做个检查:
if not os.path.exists(fullpath):
raise Exception("Path '{0}' does not exist!".format(fullpath))
zfile = zipfile.ZipFile(fullpath)
0
你遇到了一些问题。首先,'name'已经是压缩文件的名字了,你不需要对它做任何处理。其次,''.join([datadirectory, base])只是把两个名字拼接在一起,而没有加上路径分隔符。这样做应该可以解决你的问题:
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)