Skip to content

Latest commit

 

History

History
28 lines (17 loc) · 764 Bytes

python-tips.md

File metadata and controls

28 lines (17 loc) · 764 Bytes

Python Tips

1. Encoding Error

Problem

Traceback (most recent call last):
  File "build.py", line 63, in <module>
    readme.write(header)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 26-27: ordinal not in range(128)

Solved

Use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.