

This can be done by setting the optional end parameter, e.g. 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.

That being said, in most real-world scenarios this will not be an issue. On average write finished in 2.45s on my machine, whereas print took about 4 times as long (9.76s). I did a quick speed comparison and it was considerably faster than print(., file=f) when performing a large number of writes. If you are writing a lot of data and speed is a concern you should probably go with f.write(.). There is no point in using os.linesep on non-Windows systems, and it produces wrong results on Windows. And it's been that simple ever since the first port of Python to Windows. It's this simple: use \n which will be translated automatically to os.linesep. 'hi there' + os.linesep is equivalent to 'hi there\r\n', which is NOT equivalent to 'hi there\n'. There is no way that it could produce the same outcome.

> f.write('hi there' + os.linesep) # same result as previous line ?Īs expected, os.linesep does NOT produce the same outcome as '\n'. Type "help", "copyright", "credits" or "license" for more information.
