Question

In python, one can do:

print("foo bar", end="\n")

but not:

with open("foo.txt","w") as fout:
  fout.write("foo bar", end="\n")

and have to do:

with open("foo.txt","w") as fout:
  fout.write("foo bar"+"\n")

Is there a reason why? Is there a PEP for this?

Was it helpful?

Solution

This doesn't have anything in particular to do with file i/o; you can use print() to print to files just fine:

print("foo bar", end="\n", file=fout)

The .write() method of file objects just writes stuff to the files, it doesn't write lines. print(), on the other hand, by default prints a line of output. It needed the end argument for those cases when you want to print something that's not a whole line; without it, it couldn't fully replace Python 2's print statement, which includes syntax to omit the default newline.

There's no PEP about not including an end argument to .write(), because writing a PEP to keep a method how it already was in the earliest versions of Python wouldn't make any sense...

OTHER TIPS

The reason is simple, the api to write to a file is meant to be used only to write bytes, not necessarily "lines". Not everything you write to a file is text or should be handled as lines of text.

In this sense, you would need to find workarounds when you don't need a end=, or explicitly state end=''.

In the case of the print() function, quite often you are writing to stdout, which most of the times is the terminal where the notion of line is valid.

However there's nothing that prevents you from using print() to write to a file by using the file= argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top