2014-01-14 44 views
0

我有一个文件包含线,如:如何使用python提取一行中的特定数据?

754.82915: MODE1(0, 0x001900, 0x00090) 
754.82916: MODE2(0, 0x001900, 0x00090) 

如何从取数据“(”到“)”在python ??。

我试过代码:

fo=open("file1.txt","r") 
fin=open("file2.txt","w") 
lines=fo.readlines() 
for line in lines: 
    result=re.search(r'\(.*\)', line) 
    res="\n"+result.group() 
    fin.write(res) 
fo.close() 

它显示以下错误:

AttributeError: 'NoneType' object has no attribute 'group' 
+0

这就是你的文本文件的确切内容? (可能你也有一些空行) –

+1

['re.search(pattern,string,flags = 0)'](http://docs.python.org/2/library/re.html#re。搜索):如果字符串中没有位置与模式匹配,则返回无;请注意,这与在字符串中的某处找到零长度匹配不同。 –

回答

1

坚持原来的代码j最后添加一行来检查result是否为None

with open("file1.txt","r") as fin: 
    lines = fin.readlines() 
    with open("file2.txt","w") as fout: 
     for line in lines: 
      result = re.search(r'\(.*\)', line) 
      if result:  # check if not None 
       res = "\n" + result.group() 
       fout.write(res) 

你也应该从@彼得更多的pythonic答案。

1

你应该考虑使用with报表及re模块的findall()功能,像这样:

import re 

with open('file1.txt', 'r') as fin: 
    with open('file2.txt', 'w') as fout: 
     fout.write('\n'.join(re.findall(r'\(.*\)', fin.read()))) 
相关问题