码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • Python - json 美化格式、保存文件


    文章目录


    读取长篇幅的 jsonl 文件时,我们难以了解 json 的格式,复制出来贴到 sojson 之类的网站,当数据量大的时候感觉麻烦。
    不如自己写个 json 格式美化,然后保存到文件。

    text = open(file_path).readline()  # 读取 jsonl 文件的一行,及一个json 字符串
    d = json.loads(text.strip())    # 加载为字典
    json_str = json.dumps(d, indent=4, ensure_ascii=False) # 打印,缩进为 4个字符,可现实中文
    

    读取2级文件夹中对应的 jsonl 文件

    #!/usr/bin/env python
    # -*- encoding: utf-8 -*-
    
    
    import os 
    import sys 
    import json 
    
    
    root_dir = '/home/xxx/dir1'  
    save_dir = os.path.join(root_dir, 'short') 
    if not os.path.isdir(save_dir):os.makedirs(save_dir)  
    
    for ym in os.listdir(root_dir): 
        ym_dir = os.path.join(root_dir, ym)
        if not os.path.isdir(ym_dir):continue 
    
        for dir_name in os.listdir(ym_dir):
    
            dir = os.path.join(ym_dir, dir_name)  
            if not os.path.isdir(dir):continue 
    
            for file_name in os.listdir(dir):  
    
                file_path = os.path.join(dir, file_name)  
    
                text = open(file_path).readline()  
                d = json.loads(text.strip())  
                json_str = json.dumps(d, indent=4, ensure_ascii=False)
    
                print(file_name)
                save_path = os.path.join(save_dir, f'{ym}_{dir_name}_{file_name}')
    
                print(save_path)
                with open(save_path, 'w') as f:
                    f.write(json_str.strip()) 
     
    

    2024-06-05(三)

  • 相关阅读:
    【JavaScript高级】ES6常见新特性:词法环境、let、const、模板字符串、函数增强、Symbol、Set、Map
    ShowDoc后台文件上传漏洞复现 CVE-2021-41745&CNVD-2020-49480
    微服务docker部署实战
    基于STM32蓝牙控制的app智能台灯设计
    HTML:课堂练习5-3唐代诗歌目录页面设计
    【Gazebo要素01】术语和概念
    知识点2--Docker的安装
    【RF预测】基于matlab随机森林算法数据回归预测【含Matlab源码 2047期】
    uniapp封装mixins实现H5和微信小程序的微信支付
    Redis 缓存雪崩、穿透、击穿
  • 原文地址:https://blog.csdn.net/lovechris00/article/details/139467387
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号