我在使用 Python 中的 zipfile 构建的存档时遇到问题。我正在遍历目录中的所有文件并将它们写入存档。当我之后尝试提取它们时,我得到一个与路径分隔符相关的异常。
the_path= "C:\\path\\to\\folder"
zipped= cStringIO.StringIO()
zf = zipfile.ZipFile(zipped_cache, "w", zipfile.ZIP_DEFLATED)
for dirname, subdirs, files in os.walk(the_path) :
for filename in files:
zf.write(os.path.join(dirname, filename), os.path.join(dirname[1+len(the_path):], filename))
zf.extractall("C:\\destination\\path")
zf.close()
zipped_cache.close()
这是一个例外:
zipfile.BadZipfile:目录“env\index”和标题“env/index”中的文件名不同。
cStringIO.StringIO()
更新:我用一个临时文件( )替换了字符串缓冲区tempfile.mkstemp("temp.zip")
,现在它可以工作了。当 zipfile 模块写入损坏存档的缓冲区时,会发生一些事情,但不确定是什么问题。
问题是我正在从/写入以“r”/“w”模式而不是“rb”/“wb”模式打开的文件中的信息。这在 Linux 中不是问题,但由于字符编码,它在 Windows 中给了我错误。解决了。