>>> example = u'Μου αρέσει Ελληνικά'
>>> open('sample.txt', 'w').write(example)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
codecs.open('test', 'w', encoding='utf-8').write('Μου αρέσει')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/codecs.py", line 691, in write
return self.writer.write(data)
File "/usr/lib/python2.7/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 0: ordinal not in range(128)
我认为,codecs.open只是 Python 2时代的残余,当时内置的 open 具有更简单的接口和更少的功能。在 Python 2中,内置的 open不接受编码参数,所以如果您想使用二进制模式或默认编码以外的其他方式,那么应该使用 codecs.open。
In Python 2.6, the io module came to the aid to make things a bit simpler.
根据官方的 < a href = “ https://docs.python.org/2/library/io.html”rel = “ nofollow noReferrer”> 文档
New in version 2.6.
The io module provides the Python interfaces to stream handling.
Under Python 2.x, this is proposed as an alternative to the
built-in file object, but in Python 3.x it is the default
interface to access files and streams.
尽管如此,我认为在当前的情况下,codecs.open的唯一用途是向下兼容。在所有其他场景中(除非使用 Python < 2.6) ,最好使用 io.open。也在 Python 3.xio.open是相同的 built-in open