我的代码出现了问题。我试图让一个脚本工作,可以制作一个ePub文件。它们是压缩的压缩zip文件(即没有压缩)并且必须按顺序完成。当前脚本将创建一个.zip,但在运行MyObColl.Add(new MyObj("October", 3));
MyObColl.Add(new MyObj("January", 450));
MyObColl.Add(new MyObj("June", 15));
MyObColl.Add(new MyObj("Febraury", 125));
命令时,在Python Shell和终端应用程序中都无法创建错误。
有问题的错误在Python shell上如下:
Value was 450 in January
Value was 125 in Febraury
Value was 15 in June
Value was 3 in October
Mac终端上的错误(虽然我确信无论我在哪里运行zip -t
,输出都是一样的:
Traceback (most recent call last):
File "/Users/Hal/Documents/GitHub/Damore-essay-ebook/GenEpub-old.py", line 29, in <module>
if zipfile.is_zipfile(zf) is True:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/zipfile.py", line 183, in is_zipfile
result = _check_zipfile(fp=filename)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/zipfile.py", line 169, in _check_zipfile
if _EndRecData(fp):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/zipfile.py", line 241, in _EndRecData
fpin.seek(0, 2)
AttributeError: 'ZipFile' object has no attribute 'seek'
Python源代码:
zip -t
我使用的JSON文件:
Archive: IdealogicalEcho.epub
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
unzip: cannot find zipfile directory in one of IdealogicalEcho.epub or
IdealogicalEcho.epub.zip, and cannot find IdealogicalEcho.epub.ZIP, period.
答案 0 :(得分:1)
我建议您在验证之前尝试关闭。对仍然可以写入的文件执行整个文件操作可能无法提供有效的结果。
答案 1 :(得分:0)
问题出在is_zipfile
内。虽然“ filename 可能是文件或类文件对象”(13.5.1. ZipFile Objects: zipfile.is_zipfile)仍然存在,但它会因seek
错误而失败。
一种可能的解决方案是关闭文件并重新打开它以检查:
zf.close()
with open(data["fileName"] + '.epub','r') as f:
if zipfile.is_zipfile(f) is True:
print("ZIP file is valid.")
我还发现该检查非常基本,即使您手动损坏某些字节也会返回True
。实际使它失败需要一些努力。
有趣的是,明显更全面的zipfile.ZipFile.testzip
函数再次需要zf
- 但如果在zf.close()
之前调用它也会失败。并且没有zf.flush()
...
幸运的是,在运行脚本后用zip
检查创建的ePub文件显示它没有包含错误:
~/Documents $ zip -T IdealogicalEcho.epub
test of IdealogicalEcho.epub OK
(顺便说一句,不告诉你它是一个有效的 epub 。(它不是。)