Pycharm解决txt读写中文乱码问题

关键点有二:
1、代码开头
2、encoding='utf-8'说明

#!/usr/bin/python 
# -*- coding: utf-8 -*-

2、open()、read()的encoding='utf-8'说明

special_path='D:\\PythonExercises\\hello.txt'
#open(path,'w',encoding='utf-8')
addfile = open(special_path, 'w',encoding='utf-8')
addfile.write('good night!\n武汉\n')
addfile.close()
#open(path,'a',encoding='utf-8')
addfile = open(special_path, 'a',encoding='utf-8')
addfile.write('good night!\n加油!!!\n')
addfile.close()
#read(path,'r',encoding='utf-8')  'r'可省略
hellofile = open(special_path, encoding='utf-8')
# hellofile = open(special_path)
hello_contant = hellofile.read()
print(hello_contant)
hellofile.close()
  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyCharm中打开txt文件出现中文乱码问题可以通过以下方法解决: 1. 首先,你可以检查txt文件的编码格式是否为utf-8。如果不是,可以在另存为时选择utf-8编码格式保存文件。这样可以确保文件能够正确地显示中文内容。 2. 另外一种解决方法是在打开文件的时候,通过在open()函数中增加encoding='utf-8'参数来指定文件的编码格式为utf-8。例如,使用如下代码打开文件: ```python with open('file.txt', 'r', encoding='utf-8') as f: content = f.read() ``` 这样可以确保PyCharm正确地取和显示文件中的中文内容。 此外,如果使用的是Windows环境,你还可以尝试直接修改Matplotlib的配置文件来解决中文乱码问题。具体步骤如下: 1. 打开Matplotlib的配置文件matplotlibrc,可以在`C:\Users\用户名\.matplotlib`路径下找到该文件。 2. 使用文本编辑器打开matplotlibrc文件,并找到`font.family`和`font.sans-serif`这两行。 3. 将`font.family`的值设置为`SimHei`,将`font.sans-serif`的值设置为`SimHei, Arial, Times New Roman`。 这样可以设置Matplotlib使用宋体(SimHei)作为默认字体,在绘图时可以正确显示中文。 通过以上方法,你应该能够解决PyCharm中打开txt文件时出现的中文乱码问题。希望对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [pythonpycharm处理中文时遇到问题解决方法](https://blog.csdn.net/liyunlongqwert/article/details/124135402)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Pycharm解决txt读写中文乱码问题](https://blog.csdn.net/hizon1502/article/details/104665172)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值