Handling of Python coding errors

Source: Internet
Author: User
Tags in python

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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.