2012-08-01 62 views
0

因此,我在由NamedTemporaryFile函數指定的某個臨時目錄中創建了幾個文件。僅使用Python壓縮文件

zf = zipfile.ZipFile(zipPath, mode='w') 
for file in files: 
    with NamedTemporaryFile(mode='w+b', bufsize=-1, prefix='tmp') as tempFile: 
     tempPath = tempFile.name 
    with open(tempPath, 'w') as f: 
     write stuff to tempPath with contents of the variable 'file' 
    zf.write(tempPath) 

zf.close() 

當我使用這些文件的路徑添加到zip文件時,temp目錄本身會被壓縮。
當我嘗試解壓縮時,我得到一系列臨時文件夾,最終包含我想要的文件。
(即我得到文件夾Users,其中包含我的user_id文件夾,其中包含AppData ...)。

有沒有辦法直接添加文件,沒有文件夾,這樣,當我解壓時,我直接獲取文件?非常感謝!

+0

從python 2.7開始,你可以使用ZipFile作爲上下文管理器:'用zipfile.ZipFile(zipPath,mode ='w')作爲zf' – Emmanuel 2012-08-01 12:53:08

+0

我被2.6.6卡住了。否則,我會用它 – jh314 2012-08-01 13:00:35

回答

2

嘗試給arcname:

from os import path 

zf = zipfile.ZipFile(zipPath, mode='w') 
for file in files: 
    with NamedTemporaryFile(mode='w+b', bufsize=-1, prefix='tmp') as tempFile: 
     tempPath = tempFile.name 
    with open(tempPath, 'w') as f: 
     write stuff to tempPath with contents of the variable 'file' 
    zf.write(tempPath,arcname=path.basename(tempPath)) 

zf.close() 

使用os.path.basename你可以從路徑獲取該文件的名稱。根據zipfile文檔,arcname的默認值是沒有驅動器號的文件名,並且刪除了前導路徑分隔符。

1

嘗試使用arcname參數zf.write

zf.write(tempPath, arcname='Users/mrb0/Documents/things.txt') 

不知道更多關於你的計劃,你可能會發現更容易從你的最外層循環的file變量讓你arcname,而不是從派生的新名稱tempPath