我想将要提取的文件的名称更改为新名称:
i = 0
for file in zip_file.namelist():
path = 'C:\test\object'
zip_file.extract(file, path) #Change name here of file
i+=1
是否可以将file
的名称更改为str(i)+'_'+'file'
之类的名称?我知道我可以使用 shutil.move()
,但如果可能的话,我想保持我的风格。
最佳答案
您可以通过 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”的局部变量,因为它是内置类型。
关于python - 使用 zipfile python 更改文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17096701/