json转txt代码python
时间: 2024-05-08 12:12:41 浏览: 8
当你想要将JSON数据转换为文本文件时,你可以使用Python中的json模块来实现。下面是一个简单的示例代码:
```python
import json
def json_to_txt(json_data, file_path):
with open(file_path, 'w') as file:
json.dump(json_data, file)
# 示例数据
json_data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 调用函数将JSON数据转换为文本文件
json_to_txt(json_data, 'data.txt')
```
上述代码中,我们定义了一个`json_to_txt`函数,该函数接受两个参数:`json_data`要转换的JSON数据,`file_path`表示要保存的文本文件路径。在函数内部,我们使用`open`函数打文件,并使用`json.dump`将JSON数据写入文件中。
你可以根据自己的需求修改示例代码,并将其保存为一个Python脚本文件。运行该脚本后,将会生成一个名为"data.txt"的文本文件,其中包含了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文件。
json转为yolo txt python代码
下面是将JSON转换为YOLO txt的Python代码:
```python
import json
import os
# json文件路径
json_file = 'path/to/your/json/file.json'
# 类别名
classes = ["class1", "class2", "class3"]
# yolo txt文件路径
txt_file = 'path/to/your/yolo/txt/file.txt'
# 图像路径
img_dir = 'path/to/your/image/directory'
# 读取json文件
with open(json_file, 'r') as f:
data = json.load(f)
# 解析json数据并写入yolo txt文件
with open(txt_file, 'w') as f:
for img in data:
img_filename = img['filename']
img_width = img['width']
img_height = img['height']
for obj in img['objects']:
class_name = obj['classTitle']
if class_name not in classes:
continue
class_id = classes.index(class_name)
x, y, w, h = obj['points']['exterior'][0] + obj['points']['exterior'][1]
x = x / img_width
y = y / img_height
w = w / img_width
h = h / img_height
line = str(class_id) + ' ' + str(x) + ' ' + str(y) + ' ' + str(w) + ' ' + str(h) + '\n'
f.write(os.path.join(img_dir, img_filename) + ' ' + line)
print('Convert Done!')
```
其中,需要将`path/to/your/json/file.json`、`path/to/your/yolo/txt/file.txt`和`path/to/your/image/directory`替换为实际的路径。在`classes`列表中,需要按照实际需要定义类别名。运行代码后,会在指定的路径下生成YOLO txt文件。