Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: replace line in file starting with a pattern

Tags:

python

In a text file there is this line

initial_mass = unknown_int 

I want to replace the line with

initial_mass = known_int 

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

I am thinking along the lines of

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

How can I set old to the line containing initial_mass = uknown_int? I have looked at startswith() but I don't know how to use that to get what I want. I've also tried regex and find it utterly confusing.

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

like image 210
astromonerd Avatar asked Sep 09 '14 16:09

astromonerd


1 Answers

You don't need to know what old is; just redefine the entire 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)
like image 87
unutbu Avatar answered Oct 05 '22 07:10

unutbu