If you plan to save some python string into a file and encounter this UnicodeEncodeError: ‘gbk’ codec can’t encode character, this tutorial will help you. In this tutorial, we will introduce how to fix this error, you can do that by following our steps.
Question
1. I get a web page by our python crawler.
This page is Content-Type:utf-8
2.I save the content of this web page into a file with
fh.write(content)
How to fix this error when save a string to a file?
The key is add encoding when open this file.
fh = open(file_name, 'w', encoding="utf-8") fh.write(contents)
Then this error is fixed.