File I/O
suggest changeFiles opened in a non-binary mode (e.g. 'r' or 'w') deal with strings. The default encoding is the locale encoding, from locale.getencoding(), not necessarily UTF-8. It is often UTF-8. On Windows it may be a legacy code page such as cp1252.
open(fn, mode='r') # read text with the locale encoding
open(fn, mode='r', encoding='utf16') # opens file for reading utf16
# TypeError: write() argument must be str, not bytes
open("foo.txt", "w").write(b"foo")
Files opened in a binary mode (e.g. 'rb' or 'wb') deal with bytes. Passing encoding raises ValueError: binary mode doesn't take an encoding argument.
open(fn, mode='wb') # open file for writing bytes
# TypeError: a bytes-like object is required, not 'str'
open(fn, mode='wb').write("hi")
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents