Daily Reading 3
FileIO & Exceptions
What is the purpose of the ‘with’ statement when opening a file in Python, and how does it help manage resources while reading and writing files?
Opening a file via a with
command allows you to interact with the file exclusively in the context of an indented function-like block of code, called a context manager. If you do not use the with command, the file will be opened at your request, but stay open forever, until explicitly told to be closed, which can be a source of messy code or memory leaks as you open more and more files, which can also lead to a program crash.
By using a with
and working within the indented function, as soon as the function is exited for any reason, the file is automatically closed, keeping all of your interactions with the file in one place, and making issues relating to failing to close files impossible.
Explain the difference between the ‘read()’ and ‘readline()’ methods for file objects in Python. Provide examples of when to use each method.
read()
is a method that, when used within a context manager with a file open, will collect the contents of the file for putting into a variable, where it can be modified further. read()
can take one optional argument. If no argument is given, read()
will return the full file’s data, whatever it’s size. if given an argument in the form of a number (read(23)
) the method will return the first 23 characters of the file. note that calling the read method repeatedly will continue where it “left off” on its last usage, so for the example above calling read(10)
will return the 24th through 34th characters of the file.
readline()
is a similar method, but treats newlines of a text file as demarcation points, treating each line as being separate entities, like a python dictionary. This behaves in the same way in some regards however, as calling multiple times in the same context manager will return the line starting where the previous call left off.
read
could be used for when a partial duplicate of a text file is needed, or if a duplicate of only the content between characters 200 and 500 are needed, where readline
would be better suited for text documents that are formatted in a way where newlines are significant in some way, and are perfect for converting such text files into python dictionaries.
Briefly describe the concept of exception handling in Python. How can the ‘try’, ‘except’, and ‘finally’ blocks be used to handle exceptions and ensure proper execution of code? Provide a simple example.
try
and except
are a pair of methods that go together, that typically serve the purpose of seeing if your python program is capable of doing a command under the system configuration currently being used, before the command is actually called. This allows you to catch an error in advance, and, for example, print out a custom error message that is more sensible to the end user.
Try functions a fair bit like an if statement, but instead of searching for a truthy or falsy value, it’s searching to see if the line of code provided throws an error. If an error is detected, the try block is exited, and the except
block is entered, and the exception code inside is run.
The except
block supports lots of different types of errors detected, and if multiple are present, python will pick the one that exactly matches the error type encountered. If none of the listed excepts match the error type, and there is no generic except block, then python’s error handling will treat the exception as normal, giving a verbose traceback error message.
If a try
does not find any exceptions in the code it runs, then it will move on to its (optional) else block to run that code. There is also the finally
optional code block, which will be run at the end, after any other except
or else
have been performed, regardless of whether any exceptions were actually found.