2016-08-17 104 views
-3

我需要在python3中構建一個簡單的腳本,在目錄中打開更多文件,並查看這些文件內部是否爲關鍵字。如何在目錄中打開多個文件

所有目錄中的文件是這樣的: 「F * .formatoffile」(*爲休閒號碼保持)

例子:

f9993546.txt 
f10916138.txt 
f6325802.txt 

Obviusly我只需要打開txt文件那些。

在此先感謝!

最終腳本:

import os 

Path = "path of files" 
filelist = os.listdir(Path) 
for x in filelist: 
    if x.endswith(".txt"): 
     try: 
      with open(Path + x, "r", encoding="ascii") as y: 
       for line in y: 
        if "firefox" in line: 
         print ("Found in %s !" % (x)) 
     except: 
      pass 
+1

你可能想打開一個文件後,其他檢查它。 谷歌「循環目錄python」,它會告訴你如何,然後發佈你的代碼,如果你卡住了 – 576i

+2

如果它總是相同的目錄,你可以嘗試查看['glob.glob'](https:/ /docs.python.org/3/library/glob.html#glob.glob)。 –

+0

解決了。不管怎麼說,還是要謝謝你! – Sperly1987

回答

1

這應該做的伎倆:

import os 
Path = "path of the txt files" 
filelist = os.listdir(Path) 
for i in filelist: 
    if i.endswith(".txt"): # You could also add "and i.startswith('f') 
     with open(Path + i, 'r') as f: 
      for line in f: 
       # Here you can check (with regex, if, or whatever if the keyword is in the document.) 
+0

我會檢查它是否有效 – Sperly1987

+0

我試過了,出現了問題。該腳本是好的,但我只是意識到txt文件都是不同的編碼,實際上它說我:[code] UnicodeDecodeError:'utf-8'編解碼器無法解碼位置5637字節0xe7:無效的連續字節[/ code]有沒有辦法強制編碼的所有組合,直到腳本找到合適的編碼? – Sperly1987

+0

我解決了!我只是使用「ascii」,它似乎是最常用的編碼,然後我添加了一個try-except,並在2秒內找到了我正在尋找的文件!再次感謝。我會在主文章上發佈最終腳本 – Sperly1987

相關問題