File IO
So far through this book, when our examples touch files, we've operated entirely on text files. Operating systems, however, actually represent files as a sequence of bytes, not text.
Because reading bytes and converting the data to text is one of the more common operations on files, Python wraps the incoming (or outgoing) stream of bytes with appropriate decode
(or encode
) calls so we can deal directly with str
objects. This saves us a lot of boilerplate code to be constantly encoding and decoding text.
The open()
function is used to open a file. For reading text from a file, we only need to pass the filename into the function. The file will be opened for reading, and the bytes will be converted to text using the platform default encoding. As with decode
and encode
on bytes
and str
objects, the open function can accept encoding
and errors
arguments to open a text file in a specific character encoding or to choose a specific replacement strategy for invalid bytes in that encoding. These...