在 Python 中重命名 ZipFile [英] Renaming ZipFile in Python
问题描述
要重命名我正在下载的 ZipFile 中的一个文件,我执行以下操作:
To rename the one file in a ZipFile that I'm downloading, I do the following:
for item in zipfile.infolist():
old_name = item.filename
match = re.search(r'(.*)(.mdb)', item.filename)
item.filename = "%s_friend%s" % (match.group(1),, match.group(2)) # I should probably be using replace here
zipfile.extract(old_name, save_dir)
但是,当我想提取该文件并将其保存到特定目录时,我需要引用old_name"而不能引用新的.是否有一种更干净"的方式来提取重命名的文件?还是先提取然后重命名文件更像pythonic?
However when I want to extract that file and save it into a specific directory, I need to reference the "old_name" and cannot reference the new. Is there a "cleaner" way of both extracting the renamed file? Or is it more pythonic to first extract and then rename the file?
就像这个SO问题的OP,我在引用重命名的文件时遇到了同样的错误.
Like the OP of this SO question, I run into the same error when referencing the renamed file.
更新:这没有正确更新第一个文件.虽然它似乎正确地重命名了文件,但它输出了最初命名的文件.
updated: This isn't correctly updating the first file. Though it appears to rename the file properly, it output the originally named file.
for item in zipfile.infolist():
old_name = item.filename
match = re.search(r'(.*)(.mdb)', item.filename)
print match.group(1), match.group(2)
item.filename = "%s_%s%s" % (match.group(1), year, match.group(2))
print item.filename
zipfile.close()
with ZipFile(curr_zip, 'r') as zpf:
for item in zpf.infolist():
zpf.extract(item.filename, save_dir)
推荐答案
经过测试发现无法直接重命名zip文件夹内的文件.您所能做的就是创建一个全新的 zip 文件,然后使用不同的名称将这些文件重新添加到新的 zip 文件中.
After testing found that it is not possible to directly rename the file inside a zip folder. All you can do would be to n create a completely new zipfile and add the files back to the new zip file using different name.
示例代码 -
source = ZipFile('source.zip', 'r')
target = ZipFile('target.zip', 'w', ZIP_DEFLATED)
for file in source.filelist:
if not <filename_to_change>:
target.writestr(file.filename, source.read(file.filename))
else:
target.writestr('newfilename', source.read(file.filename))
target.close()
source.close()
这篇关于在 Python 中重命名 ZipFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!