views:

102

answers:

3

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

+2  A: 

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

Noufal Ibrahim
+1  A: 

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
This worked prefect! Thanks for the help
Aaron
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
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
@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
A: 

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