11

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.

2
  • Perhaps this kind of thing would be easier with sed/awk Commented Sep 9, 2014 at 16:03
  • I am unfamiliar with sed/awk. I also find sed utterly confusing. Could you write with commentary the code you are thinking would achieve the same purpose? Commented Sep 9, 2014 at 16:23

1 Answer 1

22

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)
Sign up to request clarification or add additional context in comments.

5 Comments

This is not working for me. The code compiles but no changes are made in the file.
To note, the unknown and known values are part of the string, and not typed numbers. I see the \n represents numbers. I tried removing it and replacing it with \s for string, but the file remains unchanged.
I tested the code on a sample file; it works for me. I don't see a plausible reason why it should not be working for you (assuming the obvious stuff like the filename is correct -- which is probably true since you do not report an OSError, and assuming the lines actually do begin with 'initial_mass = '.) The \n represents a new line character. It should not be changed to \s.
Do white spaces count? EDIT: yeah they do!
Whitespace is important. If the lines begin with spaces, line.startswith('initial_mass = ') will be False. That would explain the problem. You could use line.strip().startswith('initial_mass = ') instead, however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.