I have Python 2 code which looks like example a), and I think about whether I should leave it for Python 3 or convert it to binary and writing it in binary mode.
from datetime import datetime
# a
with open("check.log", "a") as f:
content = "started at: %s\n" % datetime.today()
f.write(content)
# b
with open("check.log", "ab") as f:
content = "started at: %s\n" % datetime.today()
content = content.encode("utf-8")
f.write(content)
With both ways the text in the file looks the same. At least on my Ubuntu dev machine.
I’d appreciate any insight why this possible does not make any difference - or maybe when this makes a difference.
In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding.
So your first code snippet may or may not use UTF-8 encoding, e.g. on Windows it probably will not, currently. The second code snippet explicitly uses UTF-8.
When writing output to the stream, if newline is None , any '\n' characters written are translated to the system default line separator, os.linesep.
So your first code snippet may write \n or e.g. \r\n on Windows. The second code snippet will always write \n.