12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python 2/3系共存について困ったことのメモ

Last updated at Posted at 2017-02-18

Python 2.x --> Python 3.x 移行および互換コードを書くのに困ったことをほぼ自分のメモとして時々追加します。

Python 2.7には標準open関数の引数にencodingが存在しない

Python 3系ではopen関数の引数のencodingが使えますが、Python 2系には無い。

# 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())

Python 2系で同じことをするには、ファイルをバイナリモードで開いて、内容をデコードするか、

# 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"))

ioモジュールのopenを使うか。

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())

Python3.xではio.openはbuilt-inのopenへのエイリアスになっているので、Python 2系ではio.openを使うのがよさそう。

追記:
codecs.openもPython 2/3互換であるとのコメントを頂きました。ありがとうございます。

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())
12
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?