简体   繁体   中英

Python: replace line in file starting with a pattern

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM