python--Write error Unicodeencodeerror workaround

Source: Internet
Author: User

In the process of writing a Python crawler, sometimes the result is written to a TXT file, but you will encounter Unicodeencodeerror.

Cause of error--

An error occurred while writing the contents of the file to the file.

The reason for the error is that the Python system, using the default encoding type, here ASCII, goes to write the corresponding content to the file. However, due to some of the content, ASCII encoding is not supported, so error.

Solution--

Google, Baidu found a solution has two, summarized and recorded:

1.

Import sysreload (SYS) sys.setdefaultencoding (' Utf-8 ')

2.

A better approach is to create a specific UTF-8 code for the file at the time of the output.  Without changing the default encoding. Instead of opening the file with open, use the codecs

Import Codecs

fp = Codecs.open (' output.txt ', ' A + ', ' utf-8 ')http://www.qwangxiao.com/t/wenzhang.html

Fp.write (Row[1])

Fp.close ()

python--Write error Unicodeencodeerror workaround

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.