目录

Python系列json文件处理

【Python系列】json文件处理

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

https://i-blog.csdnimg.cn/blog_migrate/5b7d56665d406fee3159289ac61fa974.jpeg#pic_center

  • 推荐: ,持续学习,不断总结,共同进步,活到老学到老
  • 导航
    • :全面总结 java 核心技术,jvm,并发编程 redis,kafka,Spring,微服务等
    • :常用的开发工具,IDEA,Mac,Alfred,Git,typora 等
    • :详细总结了常用数据库 mysql 技术点,以及工作中遇到的 mysql 问题等
    • :提供各种软件服务,承接各种毕业设计,毕业论文等
    • :总结好用的命令,解放双手不香吗?能用一个命令完成绝不用两个操作
    • :总结数据结构和算法,不同类型针对性训练,提升编程思维,剑指大厂

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

博客目录

1.需求背景

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

https://i-blog.csdnimg.cn/direct/ada27d49ba3542a68f70d942b0f71a3e.png#pic_center

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)

https://i-blog.csdnimg.cn/direct/b75cc029851a489b9a23e50347e69371.png#pic_center

觉得有用的话点个赞 👍🏻 呗。

❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!😄😄😄

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

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

https://i-blog.csdnimg.cn/blog_migrate/101469850485989da7dda6f53e80e19d.gif#pic_center