Python 如何在zip文件中更新一个文件?
我有这个zip文件结构 zipfile name=Python 如何在zip文件中更新一个文件?,python,zipfile,Python,Zipfile,我有这个zip文件结构 zipfile name=filename.zip filename> images> style.css default.js index.html 我只想更新index.html。我试图更新index.html,但它在1.zip文件中只包含index.html文件,其他文件被删除 这是我尝试的代码: import zipfile msg = 'This data did
filename.zip
filename> images>
style.css
default.js
index.html
我只想更新index.html
。我试图更新index.html
,但它在1.zip文件中只包含index.html
文件,其他文件被删除
这是我尝试的代码:
import zipfile
msg = 'This data did not exist in a file before being added to the ZIP file'
zf = zipfile.ZipFile('1.zip',
mode='w',
)
try:
zf.writestr('index.html', msg)
finally:
zf.close()
print zf.read('index.html')
那么,如何使用Python只更新
index.html
文件呢?不可能更新现有文件。
您需要读取要编辑的文件并创建一个新的存档,包括您编辑的文件和原始存档中最初存在的其他文件
下面是一些可能有帮助的问题
不支持在ZIP中更新文件。您需要重建一个没有该文件的新存档,然后添加更新版本
import os
import zipfile
import tempfile
def updateZip(zipname, filename, data):
# generate a temp file
tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
os.close(tmpfd)
# create a temp copy of the archive without filename
with zipfile.ZipFile(zipname, 'r') as zin:
with zipfile.ZipFile(tmpname, 'w') as zout:
zout.comment = zin.comment # preserve the comment
for item in zin.infolist():
if item.filename != filename:
zout.writestr(item, zin.read(item.filename))
# replace with the temp archive
os.remove(zipname)
os.rename(tmpname, zipname)
# now add filename with its new data
with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr(filename, data)
msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)
请注意,在Python2.6及更早版本中需要contextlib,因为ZipFile也是一个上下文管理器,仅从2.7开始
您可能需要检查您的文件是否确实存在于存档中,以避免无用的存档重建。到目前为止您尝试了什么?向我们展示你的代码,并描述什么有效,什么无效。只是想说声谢谢,这个脚本帮了我很多忙!我对临时文件的管理略有不同:首先,
从tempfile import NamedTemporaryFile
开始,然后要使用temp文件,我只需将函数的其余部分放在中,将NamedTemporaryFile()作为tmp\u文件:
并获得名称:tmpname=os.path.basename(tmp\u file.name)
。最后,我不再使用os.rename(…)
而是shutil.copyfile(tmpname,filename)
。临时文件最终由上下文管理器处理和关闭。