.dat文件转换为.json文件

Python实现.dat文件转换为.json文件

import json

# .dat 文件路径
# 转化为自己的.dat文件路径
dat_file_path = r'C:\Users\N\Desktop\file\data\structure.dat'
# 输出的 JSON 文件路径
# 转化为自己的.json文件路径
json_file_path = r'C:\Users\N\Desktop\file\data\structure.json'

def parse_line(parts):
    data_type = parts[2]
    if data_type == "GATE":
        return {
            "name": parts[0],
            "mileage": parts[1],
            "type": data_type,
            "hole_number": parts[3],
            "width": parts[4],
            "base_height": parts[5],
            "opening_type": parts[6],
            "opening_value": parts[7],
            "direction": parts[8]
        }
    elif data_type == "PUMP":
        return {
            "name": parts[0],
            "mileage": parts[1],
            "type": data_type,
            "unit_number": parts[3],
            "flow_per_unit": parts[4],
            "meaningless": parts[5],
            "opening_type": parts[6],
            "opening_value": parts[7],
            "direction": parts[8]
        }

data_list = []  # 初始化数据列表

# 读取 .dat 文件并转换数据
with open(dat_file_path, 'r') as dat_file:
    for line in dat_file:
        if not line.strip():  # 跳过空行
            continue
        parts = line.strip().split('\t')
        data = parse_line(parts)
        if data:
            data_list.append(data)

# 将数据写入 JSON 文件
with open(json_file_path, 'w') as json_file:
    json.dump(data_list, json_file, indent=4)

print(f"Data has been successfully converted and saved to {json_file_path}")

如果所有的数据类型都一样,不需要加以区分,也可以使用如下方法。

import json

# .dat 文件路径
# 转化为自己的.dat文件路径
dat_file_path = r'C:\Users\N\Desktop\file\data\structure.dat'
# 输出的 JSON 文件路径
# 转化为自己的.json文件路径
json_file_path = r'C:\Users\N\Desktop\file\data\structure.json'

# 读取 .dat 文件
data_list = []  # 用于存储转换后的数据
with open(dat_file_path, 'r') as dat_file:
    for line in dat_file:
        if not line.strip():  # 跳过空行
            continue
        parts = line.strip().split('\t')  # 假设数据由制表符分隔
        # 将数据行转换为字典格式
        data = {
            "name": parts[0],
            "value": parts[1],
            "mileage": parts[2],
            "number": parts[3],
            "size": parts[4],
            "value": parts[5],
            "character": parts[6],
            "type_numbers": parts[7],
            "direction": parts[8]
        }
        data_list.append(data)

# 将数据写入 JSON 文件
with open(json_file_path, 'w') as json_file:
    json.dump(data_list, json_file, indent=4)

json_file_path

data部分需要替换内容

 data = {
            "part1": parts[0],
            "part2": parts[1],
            # 添加其他的字段...
        }
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值