2011-02-11 52 views
0

我有一個巨大的文件,其內容是通過在不同的輸入文件上反覆運行可執行文件生成的。該文件的模式是這樣的: - 文件名後跟任意數量的文本行。當讀取輸入數據時出現錯誤,我必須拿起文件的名稱,我不確定最好的方法是什麼。另一個問題是,無論如何,短語中出現錯誤(最終擬合誤差是(某個數值))這個詞需要忽略。查找文件中的錯誤

C:\temptest\blahblah1 
.. (arbitrary # of text lines) 
Final fitting error : (some number) [I have to ignore this] 
C:\temptest\blahblah2 
.. (arbitrary # of text lines) 
Error could not read data !** [I have to pick up blahblah2 and copy the file to another directory, but just logging the name would suffice] 

在此先感謝!

+0

你控制輸出?即你能改變它的格式嗎? – ulidtko 2011-02-11 23:48:50

+0

我不控制文本行,但我可以在每個新文件之前插入一些特殊字符以標記正在處理的新文件。 – Illusionist 2011-02-11 23:51:25

回答

0

採用特殊的存在無論頭部要附加到文件中的行:

[line[len(special):].strip() for line in file if line.startswith(special)] 

你可以使用正則表達式還,但它會更穩健添加自己的頭,除非你確信任意線可能不以有效的文件名開頭。

1

這應該做或多或少你所需要的:

f = open("your_file.txt") 
file_name = None 
for line in f: 
    if line.startswith(r"C:\"): 
     file_name = line 
    elif line.startswith("Error"): 
     print "Error for file " + file_name 

假設:
    - 文件名將啓動「C:\」,如果這是不正確的使用正則表達式執行更準確的匹配或在新文件之前插入特殊字符,如您在評論中所述。
    - 每個文件只有一個錯誤,或者爲一個文件打印多個錯誤不是問題。如果不是這種情況,請在首次打印文件錯誤時設置一些標誌,並跳過所有後續錯誤,直到找到新文件。

1

所以,你的日誌文件看起來像

{filepath}\file1 
{ 
    multiple lines 
} 
Final fitting error : 3.2 
{filepath}\file2 
{ 
    multiple lines 
} 
Error could not read data ! 

,你想造成「錯誤無法讀取數據」消息的所有文件名列表?

import re 
import os.path 

skipErrs = set("Final fitting error") 
saveErrs = set("Error could not read data") 
LOOKFOR = re.compile('(' + '|'.join(skipErrs) + '|' + '|'.join(saveErrs) + ')') 

class EOF_Exception(Exception): pass 
def getLine(f): 
    t = f.readline() 
    if t=='': 
     raise EOF_Exception('found end of file') 
    else: 
     return t.strip() 

def getFilePath(f): 
    return os.path.normpath(getLine(f)) 

errorfiles = [] 
with open('logfile.txt') as inf: 
    while True: 
     try: 
      filepath = getFilePath(inf) 

      s = getLine(f) 
      m = re.match(s) 
      while not m: 
       s = getLine(f) 
       m = re.match(s) 

      if m.group(1) in saveErrs: 
       errorfiles.append(filepath) 
     except EOF_Exception: 
      break 
0
import shutil 
f=open("file") 
o=open("log","a") 
for line in f: 
    if line.lstrip().startswith("C:"): 
     filename = line 
    if "Error" in line or "error" in line: 
     o.write(filename +"\n") 
     shutil.move(line,another_directory) 
f.close() 
o.close()