新建一个txt文本,输入内容为:中国是一个伟大的国家。
打开文本文件读取里面的内容:
textFile=open("my.txt","rt") #t表示文本文件方式
print(textFile.readline())
textFile.close()
报错如下:
原因是encoding参数默认为None,默认读取英文字符,而文本中为中文字符,故需修改encoding=‘utf-8’,从而读取文本中的中文字符。
修改后代码如下:
textFile=open("my.txt","rt",encoding='utf-8') #t表示文本文件方式
print(textFile.readline())
textFile.close()
输出:
中国是个伟大的国家!