Python 2.x-> Python 3.x I sometimes add some troubles in writing migration and compatibility code as my notes.
The encoding of the argument of the open function can be used in the Python 3 series, but it is not in the Python 2 series.
python
# OK on Python 3.x, NG on Python 2.7
with open("some_file_with_multibyte_char", "r", encoding="utf-8") as f:
print(f.read())
To do the same in Python 2 series, open the file in binary mode and decode the contents, or
python
# OK on Python 2.7 and OK on Python 3.x
with open("some_file_with_multibyte_char", "rb") as f:
print(f.read().decode(encoding="utf-8"))
Do you use open in the io module?
python
from io import open
# OK on both Python 3.x and Python 2.7
with open("some_file_with_multibyte_char", "r", encoding="utf-8") as f:
print(f.read())
In Python 3.x, io.open is an alias for built-in open, so it seems better to use io.open in Python 2 series.
Postscript:
codecs.open is also Python 2/3 We received a comment that it is compatible. Thank you very much.
#### **`python`**
```python
import codecs
# OK on both Python 3.x and Python 2.7
with codecs.open('some_file_with_multibyte_char', 'r', 'utf-8') as f:
print(f.read())
Recommended Posts