-1

Based on this answer, is there an option to rename the file when extracting it? Or what is the best solution to do so?

Didn't find anything on the documentation

Warok
  • 383
  • 1
  • 7
  • 20
  • You want to `rename` the directory after extraction or `rename` files in the directory' ? – Bhargav - Retarded Skills Sep 28 '22 at 14:30
  • In the ZIP File there will be only one file and I want to rename it like the folder (except the .zip extension ;)) – Warok Sep 28 '22 at 14:32
  • what did you try? Where is your code? Did you read documentation for `zipfile`? It has `extract()` and `read()` - and one of then can be useful for this. – furas Sep 28 '22 at 14:52

1 Answers1

2

I found two methods:

  1. Using ZipFile.read()

    You can get data from zip file using ZipFile.read() and write it with new name using standard open(), write()

    import zipfile
    
    z = zipfile.ZipFile('image.zip')
    
    for f in z.infolist():
        data = z.read(f)
        with open('new_name.png', 'wb') as fh:
            fh.write(data)
    
  2. Using zipfile.extract() with ZipInfo

    You can change name before using extract()

    import zipfile
    
    z = zipfile.ZipFile('image.zip')
    
    for f in z.infolist():
        #print(f.filename)
        #print(f.orig_filename)
        f.filename = 'new_name.png'
        z.extract(f)
    

    This version can automatically create subfolders if you use

    f.filename = 'folder/subfolder/new_name.png'
    z.extract(f)
    
    f.filename = 'new_name.png'
    z.extract(f, 'folder/subfolder')
    
furas
  • 134,197
  • 12
  • 106
  • 148