0

I have a file contains lines like:

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

How to take the data from "(" to ")" in python??.

I tried the code:

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

It showing following error:

AttributeError: 'NoneType' object has no attribute 'group' 
2
  • That's the exact content of your text file? (May be you've some empty lines as well) Commented Jan 14, 2014 at 10:27
  • 1
    re.search(pattern, string, flags=0): Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. Commented Jan 14, 2014 at 10:28

2 Answers 2

1

Sticking to your original code, just add one line to check whether result is 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)

You should also learn from @Peter's more pythonic answer.

Sign up to request clarification or add additional context in comments.

Comments

1

You should consider using the with statements and the findall() function of the re module, like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.