-1

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!

InsigMath
  • 273
  • 2
  • 7
  • 17

1 Answers1

4

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"))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thank you very much that worked :) ... the first option, I haven't tried the second option but that is probably good to know both! – InsigMath May 13 '14 at 17:07