如何使用python在一行中提取特定数据?

时间:2014-01-14 10:23:49

标签: python python-2.7

我有一个包含以下行的文件:

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' 

2 个答案:

答案 0 :(得分:1)

您应该考虑使用with语句和findall()模块的re函数,如下所示:

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())))

答案 1 :(得分:1)

坚持原始代码,只需添加一行即可检查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)

你也应该学习@Peter的更多pythonic答案。