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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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: 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
2

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.