LoginSignup
3
5

More than 5 years have passed since last update.

Python 3 対応したのでメモ

Last updated at Posted at 2014-11-06

io_bit.py, io_midi.py を Python 2 で書き始めたので、 3 対応で手当したもの。

関連) http://d.hatena.ne.jp/yoya/20141106/io_midi

  • ファイルをバイナリとして open する場合は "b" を指定する。(2 だとなくても動く)
    
    X data = open(file).read()
    O data = open(file,"rb").read()
    
    • ちなみに、3 で出るエラーはこれ。
      
      File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/codecs.py", line 313, in decode
      (result, consumed) = self._buffer_decode(data, self.errors, final)
      UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 13: invalid continuation byte
      
    • 切り出したデータもバイナリ(バイト列)になるので、比較チェックでは data == b"〜" のように bを付ける。
      
      X   chunk == "MThd"
      O   chunk == b"MThd"
      
  • has_key は使えないので in を使う。
    
    X a.has_key("x")
    O "x" in a
    
  • バイト列から1バイト切り出すのを範囲指定に書き換え。
    
    X bytes[i] # ←これだと 2 と 3 で挙動が違う
    O bytes[i:i+1] 
    
    
    $ python2 -c 'print(b"AB"[1])'
    B
    $ python3 -c 'print(b"AB"[1])'
    66
    $ python3 -c 'print(b"AB"[1:2])'
    b'B'
    
  • ハードタブをソフトタブに修正。(2だとハードタブでも動く)
3
5
0

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
3
5