Resolve Python2.7 unicodeencodeerror: ' ASCII ' codec can ' t encode exception error

Source: Internet
Author: User
Tags sqlite database python script

Today you are ready to export the contents of a SQLite database to a text document (*.txt), and the Python program is designed as follows:

12345678910111213141516171819
#-*-Coding:utf-8-*-import sqlite3 def gsel (cur):    cur.execute ("SELECT * FROM Collection") def Main ():    conn = sq Lite3.connect ("build.db3")    cur = conn.cursor ()    gsel (cur)    # conn.commit ()    rs = Cur.fetchall ()    FP = Open ("Output.txt", "W") for    row in RS:        fp.write (row[1]) # reads and writes the 2nd column data if __name__ = = ' __main__ ':    Main ()

There should be no problem with the code, Python is using version 2.7, but at run time there was an exception error Unicodeencodeerror:

Traceback (most recent):  file ' makedb.py ', line-up, in     Main ()  file ' makedb.py ', line +, in main
   
    fp.write (Row[1]) Unicodeencodeerror: ' ASCII ' codec can ' t encode characters in position 0-78:ordinal not in range (128)
   

Would have thought that the data read error, I changed the fp.write to print, the results of the data read all and displayed in the command console, to prove that the code is not a problem, carefully read the exception information, seemingly because of the coding problem: Unicode encoding and ASCII encoding incompatible, in fact, this Python script file is encoded by Utf-8, while the sq Lite3 database access is also the UTF-8 format, python default environment code can be obtained by the following method:

Import Sysprint sys.getdefaultencoding () # ' ASCII '

The ASCII encoding is essentially the way in which Python naturally calls the ASCII codec to process the character stream, and throws an exception if the character stream is not within the ASCII range (ordinal not in range (128)).

The solution is very simple, modify the default encoding mode, many friends will think of setdefaultencoding, yes, we can through sys.setdefaultencoding (' utf-8 ') To modify the current character processing mode to Utf-8 encoding mode, it is worth noting that Python throws a Attributeerror exception if it is simply called:

Traceback (most recent):  File "<stdin>", line 1, in <module>attributeerror: ' Module ' object have No attribute ' setdefaultencoding '

Actually said that Sys has no setdefaultencoding method, in fact Sys has this method, but to ask her old people need to call a reload (SYS), very strange, is it? If anyone knows the reason, he will not hesitate to enlighten me.

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

Well, with just three lines above, we're pretty good at solving this problem, and the same approach can be applied to unicodedecodeerror . Of course, this technique comes from the network, I also found other special methods, but the feeling is still more reliable, there are children's shoes said: We will be able to upgrade the Python 2.x series to the Python 3.x series, small problems do not need to upgrade it, after all, 2 to 3 still have a transition.

Finally, I changed the code from the beginning of the article to the following:

#-*-coding:utf-8-*-import sys     # 1import sqlite3 def gsel (cur):    cur.execute ("SELECT * FROM Collection") def MA In ():    reload (SYS)                         # 2    sys.setdefaultencoding (' Utf-8 ')     # 3    conn = Sqlite3.connect ("build.db3")    cur = conn.cursor ()    gsel (cur)    # conn.commit ()    rs = Cur.fetchall ()    fp = open ("Output.txt", "W") For    row in RS:        fp.write (row[1]) if __name__ = = ' __main__ ':    Main ()

Resolve Python2.7 unicodeencodeerror: ' ASCII ' codec can ' t encode exception error

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.