Python 读取文件中文乱码

问题描述

今天调试 Python  读取文件的时候发现中乱码了

读取方式

txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())

效果

E:\worksp_py\hardwary\hardway\fifteen>python ex15.py ex15.py
Here's your file ex15.py:
Type the filename again:
>ex15.py
from sys import argv

'''
鎵撳紑鏂囦欢
'''

解决方案

指定编码方式

txt = open(filename, encoding='utf-8')

print(f"Here's your file {filename}:")
print(txt.read())

或者

txt = open(filename, encoding='UTF-8')

print(f"Here's your file {filename}:")
print(txt.read())

此处大小写都可以。

posted @ 2023-05-31 07:49  晓枫的春天  阅读(216)  评论(0编辑  收藏  举报