There are two ways to open a text file in Python:
f = open(filename)
And
import codecs
f = codecs.open(filename, encoding=\
When you want to load a binary file, use
f = io.open(filename, 'b')
.
For opening a text file, always use f = io.open(filename, encoding='utf-8')
with explicit encoding.
In python 3 however open
does the same thing as io.open
and can be used instead.
Note:
codecs.open
is planned to become deprecated and replaced by io.open after its introduction in python 2.6. I would only use it if code needs to be compatible with earlier python versions. For more information on codecs and unicode in python see the Unicode HOWTO.
When you're working with text files and want transparent encoding and decoding into Unicode objects.