Home > Enterprise >  Does the file write() function append a carriage return?
Does the file write() function append a carriage return?

Time:05-22

In Python, do I need to append a '\n' to the string I'm writing so that the next string I write is not on the same line as the previous one?

Example code:

homeFilePath = "/home/myname/testFile.out"
fp = open(homeFilePath, 'w ')
fp.write("Line one")
fp.write("Line two")
fp.write("Line 3")

I'm looking for my file to contain:

Line one
Line two
Line 3

I should mention I'm using python version 2.7.5.

CodePudding user response:

You can use print instead of fp.write directly.

from __future__ import print_function


homeFilePath = "/home/myname/testFile.out"
with open(homeFilePath, 'w ') as fp:
    print("Line one", file=fp)
    print("Line two", file=fp)
    print("Line 3", file=fp)

(This is far preferable to using the equivalent print statement, print >>fp, "Line one", etc.)

CodePudding user response:

No, you do need to add a newline. Your code will give you output

Line oneLine twoLine 3

You could write your own function that appends it for you, like:

def writeNewline(fpIn, strIn):
    if (not fpIn.closed):
        fpIn.write(strIn   "\n")

You should then get the output you want using writeNewline:

fp = open(homeFilePath, 'w ')
writeNewline(fp, "Line one")
writeNewline(fp, "Line two")
writeNewline(fp, "Line 3")
fp.close()
  • Related