2015-06-20 114 views
0

要重命名的ZipFile中的一个文件,我下载的,我做了以下内容:重命名的ZipFile在Python

for item in zipfile.infolist(): 
    old_name = item.filename 
    match = re.search(r'(.*)(.mdb)', item.filename) 
    item.filename = "%s_friend%s" % (match.group(1),, match.group(2)) # I should probably be using replace here 
    zipfile.extract(old_name, save_dir) 

然而,当我想提取文件并将其保存到特定的目录,我需要引用“old_name”并且不能引用新的。是否有一种“干净”的方式来提取重命名的文件?或者,它是更pythonic首先提取,然后重命名该文件?

与OP的this SO question一样,当引用重命名文件时,我遇到了同样的错误。

已更新:这不正确地更新第一个文件。虽然它似乎正确地重命名文件,但它会输出最初命名的文件。

for item in zipfile.infolist(): 
    old_name = item.filename 
    match = re.search(r'(.*)(.mdb)', item.filename) 
    print match.group(1), match.group(2) 
    item.filename = "%s_%s%s" % (match.group(1), year, match.group(2)) 
    print item.filename 
zipfile.close() 
with ZipFile(curr_zip, 'r') as zpf: 
    for item in zpf.infolist(): 
     zpf.extract(item.filename, save_dir) 
+0

你想提取物作为你通过每一个项目?或者可以在for循环之外,在另一个for循环之内吗?如果是后者,不要在同一个for循环中提取重命名文件。取而代之的是使用zipfile.close()关闭zip文件,然后重新打开并提取文件 –

回答

1

经过测试发现,不可能直接重命名zip文件夹内的文件。你所能做的只是创建一个全新的zip文件,并使用不同的名称将文件添加回新的zip文件。

该示例代码 -

source = ZipFile('source.zip', 'r') 
target = ZipFile('target.zip', 'w', ZIP_DEFLATED) 
for file in source.filelist: 
    if not <filename_to_change>: 
     target.writestr(file.filename, source.read(file.filename)) 
    else: 
     target.writestr('newfilename', source.read(file.filename)) 
target.close() 
source.close() 
+0

我还没有保存该文件,因为我是直接从url下载... zipfile = ZipFile(StringIO(url.read())) 你是否建议先保存它,然后重命名它? – NumenorForLife

+0

是的,请尝试。 –

+0

只需将'StringIO'对象保存在一个变量中,它将包含完整的zipfile(在内存中),并且您可以将它再次包装在'ZipFile'中。 – dhke