【Python系列】json文件处理

💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。
img

非常期待和您一起在这个小小的网络世界里共同探索、学习和成长。💝💝💝 ✨✨ 欢迎订阅本专栏 ✨✨

1.需求背景

有一个文件夹,里面是 json 文件,需要写个程序遍历这些 json 文件,然后组装成新的 json 格式,并保存为 json 文件

在这里插入图片描述

2.json 格式

json文件的内容:

[
  {
    "instruction": "1",
    "input": "2",
    "output": "3"
  }
]

3.实现步骤

  1. 实现了文件夹中文件的遍历
  2. json 文件的筛选
  3. json 文件的读取
  4. 文件路径和文件名称的获取
  5. 新 json 数据的构造
  6. 新 json 文件的创建
  7. 批量生成分隔符
import os
import json
import pandas as pd
from collections import OrderedDict


def read_json_files(directory):
    # 遍历指定目录及其子目录下的所有文件
    for root, dirs, files in os.walk(directory):
        for file in files:
            res = []
            # 检查文件扩展名是否为.json
            if file.endswith('.json'):
                # 构建文件的完整路径
                file_path = os.path.join(root, file)
                # 打开并读取JSON文件
                with open(file_path, 'r', encoding='utf-8') as f:
                    try:
                        data = json.load(f)
                        print(f"File: {file_path}")
                        # 打印文件名
                        file_name = file.replace('.json', '')
                        print(f"File name: {file_name}")
                        # print(json.dumps(data, ensure_ascii=False, indent=4))

                        for item in data:
                            print(item['instruction'])
                            res.append(item['instruction'])

                        print(res)

                        # 指定JSON文件的名称和路径
                        json_file_path = f"{file_name}_new.json"

                        # 将数组写入到JSON文件中
                        with open(json_file_path, 'w', encoding='utf-8') as json_file:
                            json.dump(res, json_file, ensure_ascii=False, indent=4)

                        print("-" * 40)
                    except json.JSONDecodeError as e:
                        print(f"Error decoding JSON from {file_path}: {e}")


# 指定要遍历的文件夹路径
directory_path = '/Users/qinyingjie/Documents/python-workspace/web/chapter08-file/11-test/subject'
read_json_files(directory=directory_path)

在这里插入图片描述

觉得有用的话点个赞 👍🏻 呗。
❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!😄😄😄

💘💘💘如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!👍 👍 👍

🔥🔥🔥Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙

img

评论 30
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kwan的解忧杂货铺@新空间代码工作室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值