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设计】。

相关文章

安装PyInstaller失败问题解决

安装PyInstaller失败问题解决

这篇文章主要介绍了安装PyInstaller失败问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 pip install P...

使用numba对Python运算加速的方法

有时候需要比较大的计算量,这个时候Python的效率就很让人捉急了,此时可以考虑使用numba 进行加速,效果提升明显~ (numba 安装貌似很是繁琐,建议安装Anaconda,里面自...

python筛选出两个文件中重复行的方法

本文实例为大家分享了python脚本筛选出两个文件中重复的行数,供大家参考,具体内容如下 ''' 查找A文件中,与B文件中内容不重复的内容 ''' #!usr/bin/python...

Python实现按中文排序的方法示例

Python实现按中文排序的方法示例

本文实例讲述了Python实现按中文排序的方法。分享给大家供大家参考,具体如下: 安装中文库 sudo apt-get update sudo apt-get install lan...

python实现根据窗口标题调用窗口的方法

本文实例讲述了python实现根据窗口标题调用窗口的方法。分享给大家供大家参考。具体分析如下: 当你知道一个windows窗口的标题后,可以用下面的代码调用窗口,甚至向窗口内写入内容。...