python エンコード指定でファイルに出力

pythonで日本語を扱っていると以下のようなエラーに遭遇することが多い

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-8: ordinal not in range(128)

コーデックを指定することで、回避できる

ファイルに主力する場合は以下のようにする

import codecs

file = codecs.open('filename', 'ab', 'utf-8')
file.write(a + '\n')
file.close()