无法在Python中打开zip文件 - BadZipFile错误

时间:2013-11-13 17:27:57

标签: python

当我创建一个zip文件并尝试在同一个python代码中打开它时,为什么我会收到BadZipFile错误?

zip_file = "C:/Temp/tst_data_1022.txt"
filePath, fileName = os.path.split(zip_file)
baseFileName, fileExt = os.path.splitext(fileName)
destFtpFile = filePath + "/" + baseFileName + ".zip"

# Create the zip file and write to it
zFile = zipfile.ZipFile(destFtpFile, 'w', compression=zipfile.ZIP_DEFLATED, allowZip64=True)
zFile.write(zip_file, arcname=fileName)

# Read Zip file
zfile = zipfile.ZipFile(destFtpFile, 'r')
for name in zfile.namelist():
    (dirname, filename) = os.path.split(name)
    print "Decompressing " + filename
    filename = "C:/Temp/" + filename
    fd = open(filename,"w")
    fd.write(zfile.read(name))
    fd.close()

正确创建了zip文件。 阅读时出错:     BadZipfile:文件不是zip文件

谢谢,

1 个答案:

答案 0 :(得分:2)

您缺少对zFile.close()的调用,该调用将刷新需要写入zip文件的剩余数据,并关闭基础文件描述符。