###前提・実現したいこと
python3系で実行されることを前提に書かれた以下のコードをpython2系でも動くように書くにはどのようにすればよいでしょうか。
python3
1with open('hoge', 'wb') as f: 2 f.write('string here, and then bytes follow.\n'.encode('utf-8')) 3 arr = list(range(10) 4 f.write(bytes(arr))
ここで、冒頭でfrom builtins import bytes, str
とすることで2系でも動くことを確認しているのですが、builtins
はpipでインストールする必要があり、小さいスクリプトなので出来れば使いたくないなと考えています。
この場合、以下のように愚直に分岐するしかないのでしょうか? python2系、3系の違いについてあまり理解できていないためご教授頂けますと幸いです。よろしくお願いします。
python3
1import sys 2with open('hoge', 'wb') as f: 3 if sys.version_info >= (3,0): 4 f.write('string here, and then binary follows\n'.encode('utf-8')) 5 arr = list(range(10)) 6 f.write(bytes(arr)) 7 else: 8 f.write('string here, and then binary follows\n') 9 arr = list(range(10)) 10 f.write(''.join(list(map(chr, arr))))
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/16 10:14