python读取文本时出现的问题和解决方法
程序员文章站
2022-05-01 23:28:08
...
大家使用python操作文件的时候肯定会运到编码不对的情况,我们来看看怎么解决这些问题:
新建一个”a.txt“文件
import chardet
def other_to_utf8():
with open("a.txt", 'r') as f:
data = f.read()
with open("a.txt", "rb") as g:
detect_data = g.read()
print(chardet.detect(detect_data)['encoding'])
with open('a.txt', 'w', encoding='utf-8') as h:
h.write(data)
def utf8_to_other():
with open('a.txt', 'r', encoding="utf-8") as f:
data = f.read()
#data = data.encode("gbk") #"xxx"为你想转换的格式
with open('a.txt', 'w', encoding='gbk') as g:
g.write(data)
with open("a.txt", "rb") as g:
detect_data = g.read()
print(chardet.detect(detect_data)['encoding'])
这仨行用来查询文件的编码格式
with open("a.txt", "rb") as g:
detect_data = g.read()
print(chardet.detect(detect_data)['encoding'])
上一篇: spring boot基于profile加载配置文件
下一篇: iOS中的单例创建
推荐阅读
-
mysql启动时出现ERROR 2003 (HY000)问题的解决方法
-
layui问题之渲染数据表格时,仅出现10条数据的解决方法
-
当用python读取几十万行文本时,会出现什么状况?
-
Angularjs在初始化未完毕时出现闪烁问题的解决方法分析
-
Python遍历zip文件输出名称时出现乱码问题的解决方法
-
Excel导入数据库时出现的文本截断问题解决方案
-
Android studio Kotlin中配置GRPC和protobuf时出现的一些问题总结
-
Python os模块中的isfile()和isdir()函数均返回false问题解决方法
-
PHP 出现乱码和Sessions验证问题的解决方法!
-
Win10系统重置电脑时出现问题未进行任何更改的原因及解决方法