2016-06-07 75 views
2

我有一個zip文件,其中包含與zip文件具有相同名稱的單個文件夾(即,如果zip文件夾的名稱是1.zip那麼zip文件裏面的文件夾名稱就是1.)
現在這個文件夾包含一個文本文件,說atextfile.txt,我想打印這個文件的內容。
如果atextfile.txt正好在zip文件中,我寫了代碼。
如何讀取本身位於zip文件內的文件夾內的文件

for zip_name in glob.glob('[0-9].zip'): 
    # the zip file name one numeric digit only. 
     z=zipfile.ZipFile(zip_name) 
     with z.open('atextfile.txt') as f: 
      for line in f: 
       for word in line: 
        print word 

我不知道現在該做什麼。請幫忙。

+1

您是否嘗試向文件名添加路徑'z.open( '1/atextfile.txt')'? – mhawke

+0

我不知道文件夾的名稱(你稱之爲一個文件夾),我只是把它存儲在一個名字如1.zip的變量中。 –

回答

2

您可以將路徑名添加到您要用ZipFile.open()提取的文件名。以下是如何使用您在問題中描述的命名方案自動執行此操作:

for zip_name in glob.glob('[0-9].zip'): 
# the zip file name one numeric digit only. 
    z=zipfile.ZipFile(zip_name) 
    subdir = zip_name[:-4] # the glob pattern ensures that the file name ends with ".zip", so strip off the extension 
    with z.open('{}/atextfile.txt'.format(subdir)) as f: 
     for line in f: 
      for word in line: 
       print word 
+0

謝謝......它的工作原理應該是......但是,如果壓縮文件包含四位或五位數字(如,我不知道它包含多少位數字),可以告訴我該怎麼辦? 。如果是五位數字,我應該更改subdir = zip_name [0-4]。 –

+0

如果你可以請告訴我如何做到這一點,如果沒有。數字在文件名中是可變的。 –

+0

@DeveshYadav:這非常簡單,你幾乎可以自己回答:使用'subdir = zip_name [: - 4]'去除'.zip'擴展名。 – mhawke

相關問題