I\'m used to doing print >>f, \"hi there\"
However, it seems that print >>
is getting deprecated. What is the recommended way t
If you want to avoid using write()
or writelines()
and joining the strings with a newline yourself, you can pass all of your lines to print()
, and the newline delimiter and your file handle as keyword arguments. This snippet assumes your strings do not have trailing newlines.
print(line1, line2, sep="\n", file=f)
You don't need to put a special newline character is needed at the end, because print()
does that for you.
If you have an arbitrary number of lines in a list, you can use list expansion to pass them all to print()
.
lines = ["The Quick Brown Fox", "Lorem Ipsum"]
print(*lines, sep="\n", file=f)
It is OK to use "\n"
as the separator on Windows, because print()
will also automatically convert it to a Windows CRLF newline ("\r\n"
).