Correct way to write line to file?

Total
0
Shares

How do I write a line to a file in modern Python? I heard that this is deprecated:

print >>f, "hi there"

Also, does "n" work on all platforms, or should I use "rn" on Windows?


Solution

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:

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *