2015-11-07 116 views
0

我有一个巨大的日志文件,我想用python解析。该文件包含从这个log.txt的工作和非工作音频/视频/图像文件使用python解析文本文件

log.txt的

filename = abc.mp4 
played correctly 

filname = cdf.wav 
failed 

filename = rtg.mp3 
failed 

的内容现在的数据如何找出失败的文件名 我试图重新。搜索,但好像我没有这种做法 所以我用任何地点到达下面的方法,但到目前为止我不能顺便找出文件名

f = open('log.txt', 'r') 
for i in f.realines(): 
    if "failed" in i: 
     print "failed files: " 
f.close() 

回答

3

保存到文件名暂时的参考,然后加入它到list如果它失败:

with open('log.txt') as f: 
    result = [] 
    for line in f: 
     line = line.strip() 
     if not line: 
      continue 
     if '=' in line: 
      name = line.split('= ')[1] 
     if line == 'failed': 
      result.append(name) 

以上后,result将是一个list与所有失败的文件名。

0

您可以简单地通过添加dump变量来修改您的代码。

In[6]: f = open('test', 'r') 
for i in f.readlines(): 
    if "failed" in i : 
     print "failed files: ", dump.split('= ')[1] 
    dump = i 
f.close() 

Output 
failed files: cdf.wav 
failed files: rtg.mp3