As the title, I use Python to parse the file (the file contains Chinese) and write the other file times incorrectly:
Unicodeencodeerror: ' ASCII ' codec can ' t encode characters
Through the guidance of the Google Great God, determine the following solutions:
#coding: Utf-8import sys Reload (SYS) sys.setdefaultencoding (' Utf-8 ')
Question: Why do we need reload?
Grep-r-i ' setdefaultencoding '/usr/lib/python2.7 output is:
/usr/lib/python2.7/site.py: Sys.setdefaultencoding (encoding) # Needs Python Unicode Build!
/usr/lib/python2.7/site.py: # Remove sys.setdefaultencoding () so this users cannot change the
/usr/lib/ python2.7/site.py: if Hasattr (SYS, setdefaultencoding):
/usr/lib/python2.7/site.py: del Sys.setdefaultencoding
Binary FILE/USR/LIB/PYTHON2.7/SITE.PYC matches
Sys.setdefaultencoding del to prevent users from changing the defaultencoding, this reason for the moment really do not know.
For the Windows platform, the above approach is really not good, for Python 2.x, there is always this problem, in Python 3.x this is not a thing,
For Windows platforms,
The beginning of the file is declared as #coding =utf-8,
When writing a string, the conversion code is GBK
File.write (Str.encode (' GBK '))
Also note that: open (...) can not have any operation, only write one line at a time, so you want to use + to connect a line
# Coding=utf-8