Fixing a Python Error: UnicodeEncodeError: 'ascii' codec can't encode characters
Conclusion
Set Python’s character encoding to utf-8.
Overview
While implementing code in Python to download images from image URLs like the one below,
I ran into the error mentioned in the title.
1 | # -*- coding: utf-8 -*- |
- Specifically, it was failing here.
1 | localfile.write(img.read()) |
Environment
- CentOS Linux release 7.0.1406 (Core)
- Python 2.7.5
Checking the character encoding
When I checked interactively as shown below, it displayed ascii.
Let’s change this to utf-8.
1 | $ python |
Checking the pip path
The path is printed when you check the version.
1 | $ pip --version |
Create sitecustomize.py under site-packages
1 | vi /usr/lib/python2.7/site-packages/sitecustomize.py |
1 | import sys |
Save with the contents above.
Check the character encoding again
It is now utf-8.
1 | $ python |
This resolved the error mentioned in the title.
Fixing a Python Error: UnicodeEncodeError: 'ascii' codec can't encode characters