0

Am trying to write a python script to search and replace this line:

time residue 3 Total

with an empty line.

This is my script:

import glob


read_files = glob.glob("*.agr")

with open("out.txt", "w") as outfile:
    for f in read_files:
        with open(f, "r") as infile:
            outfile.write(infile.read())

with open("out.txt", "r") as file:
    filedata = file.read()
filedata = filedata.replace(r'#time\s+residue\s+[0-9]\s+Total', 'x')
with open("out.txt", "w") as file:
    file.write(filedata)

Using this, am not able to get any replacement. Why could that be? The rest of the code is working fine. The output file has not change to it so i suspect that the pattern cant be found.

Thank you.

0

1 Answer 1

3

The str.replace method replaces a fixed substring. Use re.sub instead if you're looking to replace a match of a regex pattern:

import re
filedata = re.sub(r'#time\s+residue\s+[0-9]\s+Total', 'x', filedata)
1
  • 1
    Thank you! this worked! Commented Feb 19, 2019 at 23:24

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.