2013-03-21 54 views
1

需要搜索成千上萬的文件,特定字符串/元,六角標籤等,但這個Python代碼伊夫只是做搜索一個文件,這將需要一個非常長的時間搜索字符串和元數據在多個文件中

def check(): 
     datafile = file('example.txt') 
     found = False 
     for line in datafile: 
      if blabla in line: 
       found = True 
       break 

     return found 

found = check() 
if found: 
    print "true" 
else: 
    print "false" 

有什麼建議麼?謝謝

回答

0

使文件名/路徑成爲函數的參數。然後你的函數可以處理任何文件,而不僅僅是一個特定的文件。然後,爲每個您希望處理的文件調用該函數。您可能想要創建要處理的文件名/路徑的列表,然後創建一個循環來爲每個文件執行所需的操作。

例如,

def check(fname): 
    datafile = open(fname) 
    found = False 
    # ... 
    return found 

files = ['a', 'b', 'c'] 
for fname in files: 
    found = check(fname) 
    if found: 
     print("true") 
    else: 
     print("false") 
0

假設文件都包含在目錄「/ foo」的:

import os, re 
#Use a re.findall() to avoid line-by-line parsing 
myrex = re.compile('blabla') 

def check(filename): 
    with open(filename) as myfile: 
     matches = myrex.findall(myfile.read()) 
     return len(matches) > 0 

os.chdir("/foo") 
#Use an os.walk() to find the names of all files in this directory 
for root,dir,files in os.walk('.'): 
    for fname in files: 
     print fname + ": " + str(check(fname)) 

如果文件被存儲在多個位置,你需要圍繞「os.chdir一個額外的環()「塊。 如果您有多種要搜索的模式,請使用另一個「re.compile()」。

這是否有助於回答您的問題?

0

您不妨考慮globos.walk來檢索文件名,但這樣的:

import fileinput 

print any(blabla in line for line in fileinput.input(['some', 'list', 'of', 'file', 'names']) 

這會自動讀取文件順序和真理的檢驗,會短路。

0

如果所有文件都在一個目錄中,您可以使用os.listdir()來獲取它們。這會給你一個列表目錄中的所有文件。從那裏,你可以訪問每個人,例如os.listdir('/home/me/myData')。如果您使用的是基於unix的系統:grep是一款功能非常強大的工具,可爲您提供很大的靈活性。你可能想要grep -r "your query" ./ > results.txt。這將爲您提供符合搜索條件的每一行,幷包含使用正則表達式的選項......並將其保存到文件中。否則,搜索了很多文件,只有蟒蛇:

def check(x): 
    return "blabla" in x 
files = os.listdir('/home/me/files') 
for f in files: 
    x = open(f, "r").read() 
    print check(x) 

我檢查功能行爲有所不同,因爲它沒有通過線和TrueFalse都印有大寫字母檢查線路。

我想你可能想知道結果來自哪個文件。 (和什麼線?)

for f in files: 
    x = open(f, "r").read().split('\n') 
    for count in range(len(x)): 
     if check(x[count]): 
      print f + " " + count + " " +x[count] 

...或任何你需要知道的。