Writing a string terminated with a newline seems to be a very common operation in file I/O, so a writeline convenience method seems like it would be an useful addition to the language. From a quick “what do you think” poll of acquaintance who use python it seems that the reactions to this idea were mostly positive.
It would be a very simple method that does something along the lines of
out.write(text)
out.write(newline)
where the implementation could be:
-
newlineis thenewlineparameter of the given IO object, or -
writelinehas signature of(data, *, newline=None)where a value ofNonewould default to thenewlineparameter, or use thestr/bytespassed.
The current most popular method for achieving this is using any method of string concatenation with write (or writelines for multiple strings) or an additional call to write that appends a newline. I’ve taken the liberty of searching the CPython GitHub repository for some real examples of this use.¹
Another real current alternative is using print(text, end=..., file=file), but I have not seen this done very often.
I would also imagine this has been talked about on the mailing list before, but I could not find any useful results from either Google or DDG.
1.
- This sphinx extension
- The interactive
python -m asyncioconsole - binhex (1) (2)
- configparser (1) (2-3)
- distutils is full of examples (e.g. (1) (2) (3)) but there are tens, potentially hundreds of uses
- json output writing
- here in nntplib
These examples are not by any means exhaustive of the standard library alone (I only skimmed through Lib/[a-n]) and this doesn’t include examples where strings are concatenated beforehand and then written out such as this demonstrative code I pulled out of thin air
output = ''
for lineno, line in enumerate(lines, start=1):
line = process(line)
output += f'{lineno} - {line}\n'
file.write(output)