#coding:utf-8 file = open("test.txt") for line in file: print (line) file.close()
报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position...
解决:
file = open("test.txt") -->
file = open("test.txt",encoding='utf-8')
即:
#coding:utf-8 file = open("test.txt",encoding='utf-8') for line in file: print (line) file.close()
说明:
#!/usr/bin/env python #设置Python解释器,告诉系统这是一个python程序
# -*- coding: UTF-8 -*- #声明文件编码为utf-8;代码文件存储时一定要将文件编码设为与开头的文件编码声明一致的编码
#代码中的字符串的默认编码与代码文件本身的编码是一致的
python的内部编码时unicode,与文件本身的编码无关
file = open("test.txt",encoding='utf-8') #以指定的编码类型(即文件本身的编码)打开文件,chardet库可以判断文件编码类型
参考:http://changfengmingzhi.blog.163.com/blog/static/1671052882013127105225964/