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 ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.