Emiliano
Emiliano

Reputation: 109

Python - regex on each line of file

I have few *.txt files which contains sentences per line. There are some text inside parentheses. I would like to remove them including parentheses and put them into the new file separated by new line. So far what I've tried

import re
import glob

with open('output.txt', 'w', encoding='utf-8') as out_file:
    for file in glob.glob('*.txt'):
        with open(file, 'r') as in_file:
            for line in in_file:
                out_file(re.sub(r'\([^)]*\)', '', line))
                out_file('\n')

During execution, I got following error:

TypeError: '_io.TextIOWrapper' object is not callable

Upvotes: 0

Views: 129

Answers (1)

out_file is not a function that you can "call". You need to call it's method write. Change

out_file(re.sub(r'\([^)]*\)', '', line))
out_file('\n')

to

out_file.write(re.sub(r'\([^)]*\)', '', line))
out_file.write('\n')

Upvotes: 1

Related Questions