python 批量json转txt
时间: 2023-09-16 22:10:25 浏览: 45
可以使用Python内置的json库来实现json转换。以下是一个示例代码:
```python
import json
# 读取json文件
with open('data.json', 'r') as f:
data = json.load(f)
# 将json转换为字符串
result = json.dumps(data)
# 将结果写入txt文件
with open('result.txt', 'w') as f:
f.write(result)
```
以上代码将把名为"data.json"的JSON文件转换为文本文件"result.txt"。您只需将"data.json"替换为您的实际文件名即可。
相关问题
json批量转txt python
要将json批量转换为txt文件,可以使用Python来实现。首先,需要使用Python内置的json模块来读取json文件,然后将其转换为txt格式并写入到txt文件中。
首先,需要引入json模块:
```python
import json
```
然后,读取json文件并将其转换为txt格式:
```python
def json_to_txt(input_file, output_file):
with open(input_file, 'r', encoding='utf-8') as f:
data = json.load(f)
with open(output_file, 'w', encoding='utf-8') as f:
for item in data:
f.write(str(item) + '\n')
```
以上代码将json文件中的数据读取出来并逐行写入到txt文件中。在函数中,input_file是输入的json文件名,output_file是输出的txt文件名。
最后,调用该函数来批量转换json文件:
```python
file_list = ['file1.json', 'file2.json', 'file3.json']
for file in file_list:
json_to_txt(file, file.replace('.json', '.txt'))
```
以上代码将会批量转换file1.json、file2.json、file3.json并分别输出为file1.txt、file2.txt、file3.txt。
通过以上方法,可以很方便地使用Python将json文件批量转换为txt文件。
python 批量读取json文件
可以使用Python内置的json模块来批量读取json文件。具体步骤如下:
1. 导入json模块和os模块。
```python
import json
import os
```
2. 定义一个函数,用于批量读取json文件。
```python
def read_json_files(folder_path):
json_data = []
for file_name in os.listdir(folder_path):
if file_name.endswith('.json'):
file_path = os.path.join(folder_path, file_name)
with open(file_path, 'r') as f:
data = json.load(f)
json_data.append(data)
return json_data
```
3. 调用函数并传入包含json文件的文件夹路径。
```python
folder_path = '/path/to/json/files'
json_data = read_json_files(folder_path)
```
这样就可以将指定文件夹下的所有json文件读取并存储在一个列表中。