前言
场景:用于读取包含空格分隔数据的txt文件,并将其转换为结构化json文件
一、txt文件转换为json数组
1.txt文件内容
地点a 116.405285 39.904989 43.5
地标b 121.473701 31.230416 4.2
观测点c 113.264385 23.129112 12.8
2.python代码
# -*- coding:utf-8 -*- # @time: 2025-02-25 20:25 # @author: 番茄君 # @file:06-txt转换json数组.py # @software: pycharm import json def txt_to_json(input_file, output_file): """ 将txt文件转换为json格式 :param input_file: 输入文件路径(如input.txt) :param output_file: 输出文件路径(如output.json) """ # 定义一个列表 data_list = [] # 读取文件并逐行处理 with open(input_file, 'r', encoding='utf-8') as f: for line in f: # 去除首尾空白字符并按空格分割 parts = line.strip().split(" ") # 验证数据格式(需包含至少4列) if len(parts) >= 4: attribute = parts[0] try: # 提取经度、纬度、高度并转换为浮点数 longitude = float(parts[1]) latitude = float(parts[2]) height = float(parts[3]) # 构建json对象 data = { "属性名": attribute, "经度": longitude, "纬度": latitude, "高度": height } data_list.append(data) except valueerror: print(f"数据格式错误,跳过行:{line}") # 生成json文件 with open(output_file, 'w', encoding='utf-8') as json_f: json.dump(data_list, json_f, ensure_ascii=false, indent=4)
3.输出结果
[ { "属性名": "地点a", "经度": 116.405285, "纬度": 39.904989, "高度": 43.5 }, { "属性名": "地标b", "经度": 121.473701, "纬度": 31.230416, "高度": 4.2 }, { "属性名": "观测点c", "经度": 113.264385, "纬度": 23.129112, "高度": 12.8 } ]
二、txt文件转换为json对象
1.txt文件
地点a 116.405285 39.904989 43.5
地标b 121.473701 31.230416 4.2
观测点c 113.264385 23.129112 12.8
2.python代码
# -*- coding:utf-8 -*- # @time: 2025-02-25 16:15 # @author: 番茄君 # @file:05-txt转换为json对象.py # @software: pycharm import json def txt_to_json(input_file, output_file): """ 将txt文件转换为嵌套json格式 :param input_file: 输入文件路径(如input.txt) :param output_file: 输出文件路径(如output.json) """ # 定义一个字典 result = {} with open(input_file, 'r', encoding='utf-8') as f: for line_num, line in enumerate(f, 1): # 清理数据并分割列 cleaned_line = line.strip() # print(line_num,line,cleaned_line) if not cleaned_line: continue # 跳过空行 columns = cleaned_line.split() # 验证数据格式 if len(columns) != 4: print(f"第{line_num}行格式错误,需要4列数据,实际列数:{len(columns)}") continue key = columns[0] try: # 提取并转换坐标数据 coordinates = { "经度": float(columns[1]), "维度": float(columns[2]), "高度": float(columns[3]) } except valueerror as e: print(f"第{line_num}行数值格式错误:{e}") continue # 检查重复键 if key in result: print(f"警告:键名'{key}'重复(第{line_num}行)") result[key] = coordinates # 生成json文件 with open(output_file, 'w', encoding='utf-8') as json_file: json.dump(result, json_file, ensure_ascii=false, indent=2) # 使用示例 txt_to_json('input.txt', 'output.json')
3.输出结果
{ "地点a": { "经度": 116.405285, "维度": 39.904989, "高度": 43.5 }, "地标b": { "经度": 121.473701, "维度": 31.230416, "高度": 4.2 }, "观测点c": { "经度": 113.264385, "维度": 23.129112, "高度": 12.8 } }
总结
到此这篇关于python读取文本文件内容转换为json格式的文章就介绍到这了,更多相关python读取文本文件内容转换json内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论