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

Get Python 3 Object Oriented Programming 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.