浅谈python中对于json写入txt文件的编码问题
作者:蜡笔小心丶 时间:2022-01-28 05:08:58
最近一直在研究python+selenium+beautifulsoup的爬虫,但是存入数据库还有写入txt文件里面的时候一直都是unicode编码的格式。
接下来就是各种翻阅文档,查找谷歌和度娘,但是都没有具体的说明是什么问题。
结果根据自己的代码发现,原来是一句代码写到后面去了。
name = json.dumps('中国你好', ensure_ascii=False) #重点就是这一句代码
date = time.strftime('%Y-%m-%d', time.localtime(time.time())) #此处是时间转换
f = codecs.open(date + '.txt', 'a', 'utf-8')
f.write('%s\n\n' % name)
f.close()
分析 json.dumps('中国你好')
'中国你好' 是ascii 字符码,而不是真正的中文。
这是因为json.dumps 序列化时对中文默认使用的ascii编码
想输出真正的中文需要指定ensure_ascii=False
json.dumps中可以放置json字符串,但是也必须指定ensure_ascii=False
json.dumps : dict转成str
来源:https://blog.csdn.net/u011615787/article/details/73089523
标签:python,json,txt
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实现批量下载ts文件并合并为mp4
2022-07-15 20:24:09
![](https://img.aspxhome.com/file/2023/0/70110_0s.png)
python使用rabbitmq实现网络爬虫示例
2022-04-20 20:11:58
php字符串过滤strip_tags()函数用法实例分析
2023-09-04 14:05:00
Python实现清除文件夹中重复视频
2023-07-25 16:20:48
![](https://img.aspxhome.com/file/2023/3/61183_0s.jpg)
教你用python控制安卓手机
2023-11-10 10:13:39
![](https://img.aspxhome.com/file/2023/4/69554_0s.png)
用Python复现二战德军enigma密码机
2022-04-12 23:22:59
![](https://img.aspxhome.com/file/2023/1/76191_0s.png)
Python3获取cookie常用三种方案
2022-10-20 02:56:19
详解Python如何使用并发模型编程
2021-10-30 06:39:23
一个jquery日期选取插件源码
2009-12-23 19:15:00
![](https://img.aspxhome.com/file/UploadPic/20101/11/2009126213743-92s.png)
PHP抽象工厂模式Abstract Factory Pattern优点与实现方式
2023-05-25 03:04:57
教你快速掌握数据库查询优化的实用技巧
2008-11-28 15:10:00
PHP registerXPathNamespace()函数讲解
2023-06-05 01:58:00
![](https://img.aspxhome.com/file/2023/8/55408_0s.png)
Python实现读取文件夹按数字排序功能
2023-08-24 02:12:45
Python+pytorch实现天气识别
2021-09-23 18:49:13
![](https://img.aspxhome.com/file/2023/6/79566_0s.png)
PHP面向对象程序设计子类扩展父类(子类重新载入父类)操作详解
2023-10-15 01:41:57
用户体验在商业利益面前什么都不是
2009-06-12 12:07:00
asp统计在线人数是实时的吗?
2010-07-14 21:07:00
word-wrap同word-break的区别
2007-10-24 20:08:00
基于PyQt5自制简单的文件内容检索小工具
2023-06-11 19:45:03
![](https://img.aspxhome.com/file/2023/0/59830_0s.png)
Django app配置多个数据库代码实例
2023-06-11 09:11:25