Summary
In this chapter, we've seen how we can use Python exceptions to write programs which work with files of various kinds. We've focused on text files, since they are easy to work with. We've also looked at parsing binary files, which often require support from the struct
module.
A file is also a context manager. The best practice is to use files in a with
statement so that the file is closed properly and all OS resources are released. In a command-line program, this may not be that important; in long-running servers, it's absolutely essential to be sure that resources don't leak from improperly closed files.
We've also looked at more complex persistence mechanisms, including the shelve
module and the SQLite database. These provide us with ways to perform CRUD operations on data objects in a file. The SQLite database requires us to use the SQL language to describe data access: this can make our programs more portable to other databases. It can also be confusing to leverage SQL in addition...