Renaming ZipFile in Python

帅比萌擦擦* 提交于 2021-01-28 19:59:26

问题


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)

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?

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)

回答1:


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.

Example code for that -

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()


来源:https://stackoverflow.com/questions/30957064/renaming-zipfile-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!