-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!

2
  • Actually it does change my file, so I don't think I need a temp file. Thanks for commenting though! Commented May 13, 2014 at 17:25
  • Ahh sorry. I didn't see the fileinput part :D Commented May 15, 2014 at 2:13

1 Answer 1

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

1 Comment

Thank you very much that worked :) ... the first option, I haven't tried the second option but that is probably good to know both!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.