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?
The python docs recommend this way:
So this is the way I usually do it :)
Statement from docs.python.org:
If you are writing a lot of data and speed is a concern you should probably go with
f.write(...)
. I did a quick speed comparison and it was considerably faster thanprint(..., file=f)
when performing a large number of writes.On average
write
finished in 2.45s on my machine, whereasprint
took about 4 times as long (9.76s). That being said, in most real-world scenarios this will not be an issue.If you choose to go with
print(..., file=f)
you will probably find that you'll want to suppress the newline from time to time, or replace it with something else. This can be done by setting the optionalend
parameter, e.g.;Whichever way you choose I'd suggest using
with
since it makes the code much easier to read.Update: This difference in performance is explained by the fact that
write
is highly buffered and returns before any writes to disk actually take place (see this answer), whereasprint
(probably) uses line buffering. A simple test for this would be to check performance for long writes as well, where the disadvantages (in terms of speed) for line buffering would be less pronounced.The performance difference now becomes much less pronounced, with an average time of 2.20s for
write
and 3.10s forprint
. If you need to concatenate a bunch of strings to get this loooong line performance will suffer, so use-cases whereprint
would be more efficient are a bit rare.Since 3.5 you can also use the pathlib for that purpose:
In Python 3 it is a function, but in Python 2 you can add this to the top of the source file:
Then you do
You should use the
print()
function which is available since Python 2.6+For Python 3 you don't need the
import
, since theprint()
function is the default.The alternative would be to use:
Quoting from Python documentation regarding newlines:
When you said Line it means some serialized characters which are ended to '\n' characters. Line should be last at some point so we should consider '\n' at the end of each line. Here is solution:
in append mode after each write the cursor move to new line, if you want to use 'w' mode you should add '\n' characters at the end of write() function: