Writing string to a file on a new line every time


Question

I want to append a newline to my string every time I call file.write(). What's the easiest way to do this in Python?

1
201
10/23/2017 3:07:15 PM

Accepted Answer

Use "\n":

file.write("My String\n")

See the Python manual for reference.

230
3/24/2017 8:00:08 PM

You can do this in two ways:

f.write("text to write\n")

or, depending on your Python version (2 or 3):

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon