💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。
- 推荐:kwan 的首页,持续学习,不断总结,共同进步,活到老学到老
- 导航
非常期待和您一起在这个小小的网络世界里共同探索、学习和成长。💝💝💝 ✨✨ 欢迎订阅本专栏 ✨✨
1.需求背景
有一个文件夹,里面是 json 文件,需要写个程序遍历这些 json 文件,然后组装成新的 json 格式,并保存为 json 文件
2.json 格式
json文件的内容:
[
{
"instruction": "1",
"input": "2",
"output": "3"
}
]
3.实现步骤
- 实现了文件夹中文件的遍历
- json 文件的筛选
- json 文件的读取
- 文件路径和文件名称的获取
- 新 json 数据的构造
- 新 json 文件的创建
- 批量生成分隔符
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 道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙