Renaming ZipFile in Python

5.3k views Asked by At

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

There are 1 answers

5
Anand S Kumar On

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