前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 通过 json 生成小文件

python 通过 json 生成小文件

作者头像
子舒
发布2023-11-17 19:48:00
1370
发布2023-11-17 19:48:00
举报
文章被收录于专栏:子舒的个人博客

记录一个方法,pyhton 通过 json 文件,在同级目录下生成对应格式的小文本。

代码语言:javascript
复制
import json

def generate_files_from_json(json_file):
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    for item in data:
        for key, value in item.items():
            if isinstance(value, list):
                for sub_item in value:
                    for sub_key, sub_value in sub_item.items():
                        if isinstance(sub_value, dict) and 'list' in sub_value:
                            for sub_sub_item in sub_value['list']:
                                if 'id' in sub_sub_item and 'css' in sub_sub_item:
                                    id_value = sub_sub_item['id']
                                    css_value = sub_sub_item['css']
                                    create_file(id_value, css_value)

def create_file(file_name, content):
    file_path = f"{file_name}.css"
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(content)

    print(f"File '{file_path}' created successfully.")

if __name__ == "__main__":
    json_file_path = 'your_json_file.json'
    generate_files_from_json(json_file_path)
代码语言:javascript
复制
import json

def generate_files_from_json(json_file):
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    for item in data:
        for key, value in item.items():
            if isinstance(value, dict) and 'list' in value:
                for sub_item in value['list']:
                    if 'id' in sub_item and 'css' in sub_item:
                        id_value = sub_item['id']
                        css_value = sub_item['css']
                        create_file(id_value, css_value)

def create_file(file_name, content):
    file_path = f"{file_name}.css"
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(content)

    print(f"File '{file_path}' created successfully.")

if __name__ == "__main__":
    json_file_path = 'your_json_file.json'
    generate_files_from_json(json_file_path)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-11-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档