6

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

Aaron
  • 2,672
  • 10
  • 28
  • 45

3 Answers3

3

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.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • So it turns out I'm running into an issue. For some reason when I do this text replace something else is happening to the file. I use a program called TextWrangler for text editing and when I try to open the file it tells me "An unexpected I/O error occurred (MacOS Error code: -36). Before this "find and replace" it opens fine. Any idea what could be causing something like this? – Aaron Jun 02 '10 at 15:22
  • I did just see that when i try to view the original file from the terminal it asks if i want to view because it is a binary file. Maybe this is the problem? – Aaron Jun 02 '10 at 15:28
  • @Aaron: Maybe you have a newline issue between two OSes? I suggest you define the problem exactly and open a new question. Try to include as much information as possible – Eli Bendersky Jun 03 '10 at 03:40
2

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

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
0

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.

gimel
  • 83,368
  • 10
  • 76
  • 104