python – Correct way to write line to file?

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(Hellon)

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 2
print(hi there, file=f)

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

The alternative would be to use:

f = open(myfile, w)
f.write(hi theren)  # python will convert n to os.linesep
f.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.

python – Correct way to write line to file?

The python docs recommend this way:

with open(file_to_write, w) as f:
    f.write(file contentsn)

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.

Leave a Reply

Your email address will not be published.