For writing string objects, yes, I’ll use the print() function, because one can use all the functionality that has been provided, rather than having to construct the object in code.
Speaking to your thread title: is that a “better” way? I think so, for that particular use case.
The only other points of note that I would pick up on is:
You’ve not coded that with a file handler.
You’ve not specified the encoding.
So, I would code that as:
file1 = "output_test1.txt"
with open(file1, mode='w', encoding='UTF-8') as output:
for x in range(9):
print(x, file=output)
Yes. The with open() loop is called a ‘file handler’ ‘context manager’ and you don’t need the .close(), because that’s taken care of when the code drops out of the loop.
print provides various “magic” (like adding new lines and spaces between items) which is handy for, quick printing to the screen, but makes it more awkward to precisely control the file contents.
Using print to write to a file hides that it’s not printing to the screen, it will make your code harder to read.
Anyway, I don’t hink I’ve ever seen print used this way in real code.
So why does print have an optional file parameter for the output? I think it is for uses like:
print("Oops something went wrong", file=sys.stderr)
That is, when you still want quick and easy printing to the screen
If you DO what to capture output similar to what would be written to the console, you can redirect stdout:
with open("console_output.txt", 'w', encoding="utf-8") as outfile:
with contextlib.redirect_stdout(outfile):
print("this should go to the file")
Well… I wouldn’t call it that. It’s a with-statement:
and a with-statement runs a context manager:
obtained from the expression (open(....)).
A context manager runs some setup code before the suite inside the
with-statement and some teardown code when you exit the suite (either by
falling through or if an exception happens).
When you write:
with open(.....) as f:
do something with f
Python obtains a file object from the open() call, and binds the name f to it (which lets you refer to it during the inner suite).
Before running the suite (“do something with f”) the with-statement
calls f.__enter__() for any setup (for a file, nothing) and after
running the suite it calls f.__exit__(.....) to do any tear down, in
this case that will close the file.
I suspect Rob might be conflating the term “file handle” with this
stuff. To me, “file handle” is a UNIX thing, the internal state of an
open file (such as its read/write poistion and whether it is open for
read and/or write etc). Some of the functions in the os model such as os.open return a “file descriptor”, which is an integer we use to
refer to the file handle in system calls.