2017-08-18 48 views
0

我使用美麗的湯從URL中取出文件,然後想要使用Python將這些文件存儲在單個壓縮文件中。以下是我的一個URL的代碼片段。如何使用python在一個zip文件中保存多個文件?

fz = zipfile.ZipFile('C:\\Users\\ADMIN\\data\\data.zip', 'w') 


response = urllib2.urlopen(url/file_name.txt) 
file = open('C:\\Users\\ADMIN\\data\\filename.txt','w') 
file.write(response.read()) 
file.close() 

fz.write('C:\\Users\\ADMIN\\data\\filename.txt',compress_type=zipfile.ZIP_DEFLATED) fz.close() 

這段代碼不適合我,任何人都可以幫我解決這個問題。得到低於錯誤:

WindowsError: [Error 2] The system cannot find the file specified: 'C:\Users\ADMIN\data\filename.txt'

但文件存在於此位置。

+0

似乎在這裏工作。 – Goyo

回答

0

用途:

fz.writestr("file_name", url.read()) 

,因爲你需要很多次。即一個writetr()每個文件。在新ZIP的開始處選擇zip的模式(放氣)。

因此,您不需要將文件保存到磁盤,然後將其打包。只需獲取html的名稱和內容並將它們提供給writestr()。 ZIP獲取'/'作爲路徑分隔符。因此,您可以使用類似於「/some_dir/some_subdir/index.html」的子目錄或「/index.html」將文件放入根目錄中。

相關問題