Python: replace line in file starting with template

The text file has this line

initial_mass = unknown_int 

      

I want to replace the line

initial_mass = known_int 

      

As the names suggest, I won't know the initial value, but I want to replace whatever is with the known value. Using Python, how do I search for a string that starts with 'initial_mass', then replace the entire string with "initial_mass = known_int"?

I think along lines

import fileinput
    for line in fileinput.FileInput(filename, inplace=True):
    line=line.replace(old, new)
    print(line),  

      

How can I set old

to the containing string initial_mass = uknown_int

? I looked at startswith()

, but I don't know how to use this to get what I want. I have also tried regex and find it completely confusing.

The file is not very large, but I will have to iterate over this process many times.

+3


source to share


1 answer


You don't need to know what it is old

; just override the whole line:



import sys
import fileinput
for line in fileinput.input([filename], inplace=True):
    if line.strip().startswith('initial_mass = '):
        line = 'initial_mass = 123\n'
    sys.stdout.write(line)

      

+6


source







All Articles