Files and Databases

The final built-in object type of Python allows us to access files. Files in Python are different from the previous types I've covered. They aren't numbers, sequences, or mappings; they only export methods for common file processing. Technically, the file is a pre-built C extension that provides a wrapper for the C stdio.h (standard input/output) library header. If you already know how to use files in other languages, there isn't much difference in Python.

Files are a way to save data permanently. Apart from a few program listings, nearly everything demonstrated so far is resident only in memory; as soon as you close down Python or turn off your computer, it goes away. You would have to retype everything over if you wanted to use it again.

The files that Python creates are manipulated by the computer's filesystem. Python is able to use operating-system-specific functions to import, save, and modify files. It actually doesn't take much to make cross-platform applications, because the Python application programming interface (API) handles a lot of the details behind the scenes. All the developer needs to know is which commands to call for a particular operation.

In this chapter, we will cover the following topics: