- Files are opened using the built-in open() function which accepts a file mode to control read/write/append behaviour and whether the file is to be treated as raw binary or encoded text data.
- For text data you should specify a text encoding.
- Text files deal with string objects and perform universal newline translation and string encoding.
- Binary files deal with bytes objects with no newline translation or encoding.
- When writing files, it's your responsibility to provide newline characters for line breaks.
- Files should always be closed after use.
- Files provide various line-oriented methods for reading, and are also iterators which yield line by line.
- Files are context managers and the with-statement can be used with context managers to ensure that clean up operations, such as closing files, are performed.
- The notion of file-like objects is loosely defined, but very useful in practice. Exercise EAFP to make the most of them.
- Context managers aren't restricted to file-like objects. We can use tools in the contextlib standard library module, such as the closing() wrapper to create our own context managers.
Along the we way found that:
- The help() function can be used on instance objects, not just types.
- Python supports bitwise operators &, |, << and >>.
-
Nor any language, for that matter.
-
You can get the full details of the with-statements syntactic equivalence in PEP 343.
-
You can learn all about the BMP format here.
-
Like, for example, sequence protocol is for tuple-like-objects.
-
Easier to Ask Forgiveness Than Permission.