snippetpythonCriticalCanonical
Correct way to write line to file?
Viewed 0 times
linewritecorrectfileway
Problem
How do I write a line to a file in modern Python? I heard that this is deprecated:
Also, does
print >>f, "hi there"Also, does
"\n" work on all platforms, or should I use "\r\n" on Windows?Solution
This should be as simple as:
From The Documentation:
Do not use
Some useful reading:
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:
- The
withstatement
open()
'a'is for append, or use
'w'to write with truncation
os(particularlyos.linesep)
Code Snippets
with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')Context
Stack Overflow Q#6159900, score: 1594
Revisions (0)
No revisions yet.