Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text in file with Python

I'm trying to replace some text in a file with a value. Everything works fine but when I look at the file after its completed there is a new (blank) line after each line in the file. Is there something I can do to prevent this from happening.

Here is the code as I have it:

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

Thank you, Aaron

like image 744
Aaron Avatar asked Jun 01 '10 17:06

Aaron


2 Answers

Each line is read from the file with its ending newline, and the print adds one of its own.

You can:

print line,

Which won't add a newline after the line.

like image 182
Eli Bendersky Avatar answered Oct 03 '22 08:10

Eli Bendersky


The print line automatically adds a newline. You'd best do a sys.stdout.write(line) instead.

like image 32
Noufal Ibrahim Avatar answered Oct 03 '22 08:10

Noufal Ibrahim