1

I want to change the name of the file I am extracting to something new:

i = 0
for file in zip_file.namelist():
     path = 'C:\test\object'
     zip_file.extract(file, path)  #Change name here of file
     i+=1

Is it possible to change the name of file to something like str(i)+'_'+'file'? I know I can use shutil.move(), but I want to maintain my style, if possible.

4

1 回答 1

3

您可以通过 zip_file 对象的 open 方法使用文件对象直接在正确的位置提取文件。

zip_file = zipfile.ZipFile('toto.zip')
target_path = 'C:\test\object'

for i, filename in enumerate(zip_file.namelist()):
    target = os.path.join(target_path, "%05d_%s" % (i, filename))
    file_obj = open(target, 'wb')
    try:
        shutil.copyfileobj(zip_file.open(filename, 'r'), file_obj)
    finally:
        file_obj.close()

顺便说一句,你应该避免使用名为“file”的局部变量,因为它是一个内置类型。

于 2013-06-13T21:42:36.800 回答