2011-09-15 52 views
3

我想知道如果有人知道我可以在我的zip文件夾(「fw/resources/logo.png」)下將名爲「logo.png」的文件重命名爲(「fw/resources /logo.png.bak「),使用python的zip模塊。使用zipmodule重命名ZIP文件夾中的文件

+1

你不能使用內置的'zipfile'模塊。 – agf

回答

3

我認爲這是不可能的:zipfile模塊沒有這個方法,正如Renaming a File/Folder inside a Zip File in Java?中提到的那樣,zip文件的內部結構也是如此。所以你必須做unzip,重命名,zip。

更新:剛剛找到 Delete file from zipfile with the ZipFile Module哪些應該可以幫到你。

+0

好吧,我將如何刪除zip文件夾中的目錄? – user715578

+0

刪除可以使用shutil.rmtree的os.rmdir完成,但是如果你只想重命名文件夾,我們可以使用shutil.move – rocksportrocker

+0

實際上,我將如何刪除zip文件夾中的文件? – user715578

2

正如rocksportrocker所提到的,您不能從zipfile歸檔文件重命名/刪除文件。您可以遍歷zipfile中的文件並選擇性地添加所需的文件。因此,要從zip文件中刪除某個目錄,您不會將它們複製到新的zip文件中。這將是這樣的:

source = ZipFile('source.zip', 'r') 
target = ZipFile('target.zip', 'w', ZIP_DEFLATED) 
for file in source.filelist: 
    if not file.filename.startswith('directory-to-remove/'): 
     target.writestr(file.filename, source.read(file.filename)) 
target.close() 
source.close() 

。這將讀取所有的文件到內存中,它不會對大型歸檔的理想解決方案。對於小型檔案館來說,這是按照廣告的方式工

+0

它是否真的將整個文件加載到內存中? – swdev