Python: UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
python3在读取中文的时候莫名其妙报了错,也知道是字符编码的问题,但是查了好多博客不是很管用
解决办法:
以这种方式进行读取就行了,编码格式为utf8,
def replace_line(file_name, line_num, text):
with open(file_name, 'r', encoding='utf8') as f:
lines = f.readlines()
lines[line_num] = text
with open(file_name, 'w', encoding='utf8') as out:
out.writelines(lines)