page

Jan 26, 2022

[python] SyntaxError: Non-ASCII character

Q.

SyntaxError: Non-ASCII character '\xc8' in file test.py on line 15, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

 

A.

1. add encoding comment to top of the .py file

#-*-encoding:utf-8-*-

 

2. set default encoding (seems not working in python3)

import sys
reload(sys)
sys.setdefaultencoding('utf-8') 


3. re-encoding with utf-8 after decodining

a=a.decode('xxx').encode('utf-8')    # 'xxx' is encoding method of string 'a'

 step1: a=a.decode('xxx').encode('utf-8')  # Decode string 'a' which is endocded with 'xxx'

 step2: a=a.decode('xxx').encode('utf-8')  # re-encode decoded string 'a' in step1 with 'utf-8'


4. set file I/O

f=open('C:/xxx/xxx.txt', 'rt', encoding='utf-8')   # read file

f=open('C:/xxx/xxx.txt', 'wt', encoding='utf-8')  # write file

No comments:

Post a Comment