So, I recently learned that it’s relatively unsafe to simply open a file, assign the return-value to avariable, and then work with the resultant file-object. That is, to do something like this:
myFile = open(myFileName, "r")
myFile.readline()
# And so on
Instead, it’s apparently safer to use a “with”-statement, along these lines:
with open(myFileName, "r") as myFile:
myFile.readline()
# and so on
This apparently guarantees correct file-closing, outside of some edge-cases.
For the most part, switching to using “with” shouldn’t be a major problem, I think. The point at which I’m uncertain, however, is in the case of log-files.
In one of my projects, I’m redirecting log-output to a text-file, like this:
sys.stdout = open("logfile.txt", "w")
sys.stderr = open("logfile.txt", "w")
The code in question happens at the start of my main module, amongst that module’s import-statements.
In this case, how would I implement the “with”-pattern? Would I enclose the entire program in it, the whole thing indented? Something else? Or is it perhaps better to no redirect output in this way at all?