有没有办法更改 Python 中使用 zipfile 提取的文件的名称?

Is there a way to change the name of the files extracted using zipfile in Python?

我正在尝试从 zip 文件夹中提取一个 csv 文件并选择其名称,因为它保存在新目录中。此代码可以很好地提取文件:

import zipfile
with zipfile.ZipFile(f'C:\Users\user\Downloads\{nombre_solar_zip}', 'r') as zip_ref:
    zip_ref.extractall('C:\Users\user\\work')

但是zip文件夹里的文件名一直在变,所以我想改个名字,这样我就可以阅读了。有什么办法吗?

您可以使用 ZipFile.infolist and then open each member, read, and write to a file of your choice with ZipFile.open 迭代成员。

加起来就是这样:

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)