txt 转 json 使用python语言

需求:

把如下的txt文档转成json输出

代码

python 复制代码
import json


def txt_to_json(input_file, output_file):
    data_list = []

    with open(input_file, 'r', encoding='utf-8') as f:
        for line in f:
            # 分割数据并去除换行符
            parts = line.strip().split(',')
            print(f"{parts}")
            print(type(parts))
            # 构造数据字典
            record = {
                "name": parts[0],
                "date": parts[1],
                "money": parts[2],
                "memo": parts[3]
            }

            data_list.append(record)


        # 写入JSON文件
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(data_list, f, ensure_ascii=False, indent=2)


# 使用示例
txt_to_json('C:/Users/kwok/Desktop/novel/bill.txt', 'C:/Users/kwok/Desktop/novel/output.json')

输出文件如下

相关推荐
linzeyang2 分钟前
Advent of Code 2025 挑战全手写代码 Day 5 - 餐厅
后端·python
wtsolutions2 分钟前
JSON导入WPS表格,JSON转wps,json2wps, WPS 插件使用指南
json·wps·wtsolutions
祝余Eleanor5 分钟前
Day 29 类的定义及参数
人工智能·python·机器学习
码界奇点15 分钟前
基于Dash+FastAPI的通用中后台管理系统设计与实现
python·车载系统·毕业设计·fastapi·源代码管理·dash
white-persist18 分钟前
【攻防世界】reverse | Mysterious 详细题解 WP
c语言·开发语言·网络·汇编·c++·python·安全
小oo呆1 小时前
【学习心得】Python好库推荐——pipx
linux·开发语言·python
smile_Iris1 小时前
Day 28 元组和OS模块
python·机器学习
ewboYang1 小时前
JSON.parse()大整数精度丢失的问题和解决方法
json
AI科技星1 小时前
时空运动的几何约束:张祥前统一场论中圆柱螺旋运动光速不变性的严格数学证明与物理诠释
服务器·数据结构·人工智能·python·科技·算法·生活
AIsdhuang1 小时前
2025 AI培训权威榜:深度评测与趋势前瞻
人工智能·python·物联网