Python遍历文件夹 处理json文件的方法

yipeiwu_com5年前Python基础

有两种做法:os.walk()、pathlib库,个人感觉pathlib库的path.glob用来匹配文件比较简单。

下面是第二种做法的实例(第一种做法百度有很多文章):

from pathlib import Path
import json

analysis_root_dir = "D:\\analysis_data\json_file"
store_result="D:\\analysis_data\\analysis_result\\dependency.csv"

def parse_dir(root_dir):
  path = Path(root_dir)

  all_json_file = list(path.glob('**/*.json'))

  parse_result = []

  for json_file in all_json_file:

    # 获取所在目录的名称
    service_name = json_file.parent.stem
    with json_file.open() as f:
      json_result = json.load(f)
    json_result["service_name"] = service_name
    parse_result.append(json_result)

  return parse_result

def write_result_in_file(write_path , write_content):

  with open(write_path,'w') as f:
    f.writelines("service_name,action,method,url\n")
    for dict_content in write_content:
       url = dict_content['url']
       method = dict_content['method']
       action = dict_content['action']
       service_name = dict_content['service_name']
       f.writelines(service_name + ","+ action+","+method + ","+ url+"\n")

def main():
  print("main begin...")
  parse_result = parse_dir(analysis_root_dir)
  print(parse_result)
  write_result_in_file(store_result,parse_result)
  print("main finished...")

if __name__ == '__main__':
  main()

运行结果

main begin...
[{'url': '/rest/webservice/v1/dosomthing', 'method': 'post', 'action': 'create', 'service_name': 'WebSubService'}, {'url': '/rest/webservice/v1/dosomthing', 'method': 'post', 'action': 'create', 'service_name': 'WebSubService01'}, {'url': '/rest/webservice/v1/dosomthing', 'method': 'post', 'action': 'create', 'service_name': 'WebSubService02'}, {'url': '/rest/webservice/v1/dosomthing', 'method': 'post', 'action': 'create', 'service_name': 'WebSubService03'}, {'url': '/rest/webservice/v1/dosomthing', 'method': 'post', 'action': 'create', 'service_name': 'WebSubService04'}, {'url': '/rest/webservice/v1/dosomthing', 'method': 'post', 'action': 'create', 'service_name': 'WebSubService05'}]
main finished...

目录结构

json file内容

{
 "url":"/rest/webservice/v1/dosomthing",
 "method":"post",
 "action":"create"
}

以上这篇Python遍历文件夹 处理json文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python增强赋值和共享引用注意事项小结

概述 Python中的增强赋值是从C语言中借鉴出来的,所以这些格式的用法大多和C一致,本身就是对表达式的简写,即二元表达式和赋值语句的结合,比如a += b 和a = a + b 就是...

Python处理session的方法整理

Python处理session的方法整理

前言: 不管是在做接口自动化还是在做UI自动化,测试人员遇到的第一个问题都是卡在登录上。 那是因为在执行登录的时候,服务端会有一种叫做session的会话机制。 一个很简单的例子:...

Python解析并读取PDF文件内容的方法

Python解析并读取PDF文件内容的方法

本文实例讲述了Python解析并读取PDF文件内容的方法。分享给大家供大家参考,具体如下: 一、问题描述 利用python,去读取pdf文本内容。 二、效果 三、运行环境 pytho...

Python语法分析之字符串格式化

前序 There should be one - and preferably only one - obvious way to do it. ———— the Zen of Pyt...

Python排序算法之选择排序定义与用法示例

Python排序算法之选择排序定义与用法示例

本文实例讲述了Python排序算法之选择排序定义与用法。分享给大家供大家参考,具体如下: 选择排序 选择排序比较好理解,好像是在一堆大小不一的球中进行选择(以从小到大,先选最小球为例):...