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 "\r\n"
on Windows?
Python writes a line to file. To write a line to a file in Python, use a with open() function. The with statement helps you to close the file without explicitly closing it.
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:
with
statementopen()
'a'
is for append, or use'w'
to write with truncationos
(particularly os.linesep
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With