Correct way to write line to file? Correct way to write line to file? python python

Correct way to write line to file?


This should be as simple as:

with open('somefile.txt', 'a') as the_file:    the_file.write('Hello\n')

From The Documentation:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

Some useful reading:


You should use the print() function which is available since Python 2.6+

from __future__ import print_function  # Only needed for Python 2print("hi there", file=f)

For Python 3 you don't need the import, since the print() function is the default.

The alternative would be to use:

f = open('myfile', 'w')f.write('hi there\n')  # python will convert \n to os.linesepf.close()  # you can omit in most cases as the destructor will call it

Quoting from Python documentation regarding newlines:

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.


The python docs recommend this way:

with open('file_to_write', 'w') as f:    f.write('file contents\n')

So this is the way I usually do it :)

Statement from docs.python.org:

It is good practice to use the 'with' keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.