Files and Resource Management

Reading and writing files is a key part of what many real-world programs do. The notion of a file, however, is somewhat abstract. In some cases a file might mean collection of bytes on a hard disk; in others cases it might mean, for example, an HTTP resource on a remote system. These two entities share some behavior. For example, you can read a sequence of bytes from each. At the same time, they're not identical. You can, for example, generally write bytes back to a local file while you can't do that with HTTP resources.

In this chapter we'll look at Python's basic support for working with files. Since dealing with local files is both common and important, we'll focus primarily on working with them. Be aware, though, that Python and its ecosystem of libraries provides similar file-like APIs for many other kinds of entities, including URI-based resources, databases, and many other sources of data. This use of a common API is very convenient and makes it easy to write code that can work against a wide range of data sources without change.

Also in this chapter we'll look at context managers, one of Python's primary means for managing resources. Context managers allow you to write code that is robust and predictable in the face of exceptions, ensuring that resources such as files are properly closed and accounted for when errors occur.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset