Python codecs module---processing data when writing to a file there is a problem of encoding not uniform

Source: Internet
Author: User

The Open method opens the file sometimes with some problems, because the open opening file can only be written to the STR type, not the string encoding.

Example:

>>> FR = open (' test.txt ',' a ')

>>> line1 = "I love the Motherland"

>>> Fr.write (line1)

When there is a code is not unified, at this time to write open mode file is a problem.

>>> line2 = u ' I love the Motherland '

>>> Fr.write (line2)

Traceback (most recent):

File "<pyshell#4>", line 1, in <module>

Fr.write (line2) Unicodeencodeerror: ' ASCII ' codec Can ' t encode characters in Position 0-11:ordinal not in range

You can use Codecs.open,

>>> import codecs

>>> fw = Codecs.open ( ' Test1.txt ', ' a ', Utf-8 ')

>> > Fw.write (line2)

>>>

Python codecs module---processing data when writing to a file there is a problem of encoding not uniform

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.