【问题标题】:Unable to open zip file in Python - BadZipFile error无法在 Python 中打开 zip 文件 - BadZipFile 错误
【发布时间】:2013-11-13 17:27:57
【问题描述】:

当我创建一个 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 文件

谢谢,

【问题讨论】:

    标签: python


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-07-11
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 2021-11-25
      • 1970-01-01
      • 2021-05-03
      • 2021-08-11
      • 2014-11-07
      相关资源
      最近更新 更多