2014-03-25 36 views
3

我有一個壓縮數據文件(全部在一個文件夾中,然後壓縮)。我想讀取每個文件而不解壓縮。我嘗試了幾種方法,但沒有用於輸入zip文件中的文件夾。我應該如何實現這一目標?如何閱讀Python中壓縮文件夾中的文本文件

沒有在zip文件夾:

with zipfile.ZipFile('data.zip') as z: 
    for filename in z.namelist(): 
    data = filename.readlines() 

有了一個文件夾:

with zipfile.ZipFile('data.zip') as z: 
     for filename in z.namelist(): 
     if filename.endswith('/'): 
      # Here is what I was stucked 

回答

10

namelist()在歸檔中返回所有項的列表遞歸。

您可以檢查一個項目是否是一個目錄通過調用os.path.isdir()

import os 
import zipfile 

with zipfile.ZipFile('archive.zip') as z: 
    for filename in z.namelist(): 
     if not os.path.isdir(filename): 
      # read the file 
      with z.open(filename) as f: 
       for line in f: 
        print line 

希望有所幫助。

1

我得到了亞歷克的代碼工作。我做了一些小修改:(注意,這將不適用於受密碼保護的zip文件)

import os 
import sys 
import zipfile 

z = zipfile.ZipFile(sys.argv[1]) # Flexibility with regard to zipfile 

for filename in z.namelist(): 
    if not os.path.isdir(filename): 
     # read the file 
     for line in z.open(filename): 
      print line 
     z.close()    # Close the file after opening it 
del z       # Cleanup (in case there's further work after this) 
相關問題