json文件转为txt
时间: 2023-09-24 10:07:12 浏览: 52
你可以使用Python中的json和io模块来将json文件转为txt文件,代码如下:
```python
import json
import io
# 打开json文件
with open('example.json', 'r', encoding='utf-8') as f:
data = json.load(f)
# 将json数据写入txt文件
with io.open('example.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False, indent=2))
```
其中,`example.json`是你要转换的json文件名,`example.txt`是转换后的txt文件名。在第一段代码中,我们使用`json.load()`方法将json文件转为Python中的字典或列表类型的数据。在第二段代码中,我们使用`io.open()`方法创建或打开一个txt文件,并使用`json.dumps()`方法将Python数据转为json格式的字符串,并写入txt文件中。
需要注意的是,`ensure_ascii=False`参数表示允许写入非ASCII字符,`indent=2`参数表示使用两个空格缩进格式化输出json字符串。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)