Question

I am trying to replace text in a text file (let's just call the file test.txt), here is the example text:

Math is good
Math is hard
Learn good math
be good at math
DO\SOMETHING\NOW

I want something like:

Math is good
Math is hard
Learn good science
be good at science
DO\SOMETHING\NOW

I am trying to use fileinput in the following way

import fileinput
file = fileinput.input("Path/To/File/text.txt", inplace=True)
for line in file:
    print(line.replace("math", "science"))

The problem is that the print function automatically attaches "\n" so it skips a new line. I tried replacing with using "sys.stdout.write(line.replace("math", "science")) but that outputed numbers in the text file. So how do I do this efficiently so that I get the results I want. Should I just use open and go line by line and checking if the word "math" pops up and replace the word? Any help would be greatly appreciated!

Was it helpful?

Solution

You can tell print() not to write a newline by setting the end keyword argument to an empty string:

print(line.replace("math", "science"), end='')

The default value for end is '\n'.

Alternatively you could remove the newline from line:

print(line.rstrip('\n').replace("math", "science"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top