Correct way to write line to file?
Posted By: Anonymous
I’m used to doing print >>f, "hi there"
However, it seems that print >>
is getting deprecated. What is the recommended way to do the line above?
Update:
Regarding all those answers with "n"
…is this universal or Unix-specific? IE, should I be doing "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:
- The
with
statement open()
- ‘a’ is for append, or use
- ‘w’ to write with truncation
os
(particularlyos.linesep
)
Answered By: Anonymous
Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.