[Python] UnicodeEncodeError: & #39; gbk & #39; codec can & #39; t encode character solution,

Source: Internet
Author: User

[Python] UnicodeEncodeError: 'gbk' codec can't encode character solution,

Compiling a python script in windows causes serious Encoding Problems.

When writing network data streams to files, we will encounter several encodings:

1: # encoding = 'xxx' here (that is, the first line of the python file) encoding refers to the encoding of the python script file itself, irrelevant. As long as XXX is the same as the file encoding. For example, you can set various encodings In the notepad ++ "format" menu. You must ensure that the encoding set in this menu is the same as encoding XXX. If the encoding is different, an error is returned.

2: The encoding of the network data stream, such as obtaining a webpage, indicates the encoding of the network data stream. Decode must be decoded to unicode encoding.

3: If the encoding of the target file is to write the encoding of the network data stream to the new file, do I need to specify the encoding of the new file. Write File Code such as f. write (txt). txt is a string decoded by decode. The encoding of the target file is the culprit of the title. If we open a file: f = open ("out.html", "w"), in windows, the default encoding of the new file is gbk, the python interpreter uses gbk encoding to parse the txt file of our network data stream. However, the txt file is now a unicode code of decode. In this case, the parsing will fail, and the above problem occurs. The solution is to change the encoding of the target file: f = open ("out.html", "w", encoding = 'utf-8 '). In this way, the problem no longer exists.

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.