'Is there a way to change the name of the files extracted using zipfile in Python?
I'm trying to extract a csv file from a zip folder and choose its name as it is saved in the new directory. This code is working well to extract the file:
import zipfile
with zipfile.ZipFile(f'C:\\Users\\user\\Downloads\\{nombre_solar_zip}', 'r') as zip_ref:
zip_ref.extractall('C:\\Users\\user\\\\work')
But the name of the file inside the zip folder is constantly changing, so I'd like to change the name so I can read it. Is there any way to do this?
Solution 1:[1]
You can iterate members with ZipFile.infolist
and then open each member, read, and write to a file of your choice with ZipFile.open
.
All together, it would be like this:
import zipfile
with zipfile.ZipFile("/path/to/my-file.zip") as zip
for member in zip.infolist():
with zip.open(member, "r") as infile, open("new-file-name", "wb") as outfile:
while True:
data = infile.read(chunk_size)
if not data:
break
outfile.write(data)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Balaïtous |