0

当我创建一个 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: File is not a zip file

谢谢,

4

1 回答 1

2

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

于 2013-11-13T17:30:11.623 回答