Replace text in file in Python

I am trying to replace some text in a file with a value. Everything works fine, but when I look at the file after it is finished, a new (empty) line appears after each line in the file. Is there something I can do to prevent this from happening.

Here is the code I have:

import fileinput for line in fileinput.FileInput("testfile.txt",inplace=1): line = line.replace("newhost",host) print line 

Thanks Aaron

+6
python file replace text
source share
3 answers

Each line read from the file with the end of a new line, and printing adds one of its own.

You can:

 print line, 

Which does not add a new line after the line.

+3
source share

print line automatically adds a new line. It is best to do sys.stdout.write(line) .

+2
source share

print adds a newline:

The character A '\ n' is written at the end if the print statement does not end with a comma. This is the only action if the statement contains only a listing of the keyword.

0
source share

All Articles