Aaron
Aaron

Reputation: 2772

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

Upvotes: 6

Views: 2881

Answers (3)

gimel
gimel

Reputation: 86492

print adds a new-line character:

A '\n' character is written at the end, unless the print statement ends with a comma. This is the only action if the statement contains just the keyword print.

Upvotes: 0

Eli Bendersky
Eli Bendersky

Reputation: 273816

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.

Upvotes: 3

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72855

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

Upvotes: 2

Related Questions