您好,欢迎来到爱go旅游网。
搜索
您的当前位置:首页Python遍历文件夹处理json文件的方法

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

来源:爱go旅游网
Python遍历⽂件夹处理json⽂件的⽅法

有两种做法:os.walk()、pathlib库,个⼈感觉pathlib库的path.glob⽤来匹配⽂件⽐较简单。下⾯是第⼆种做法的实例(第⼀种做法百度有很多⽂章):

from pathlib import Pathimport 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 + \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', 'methmain finished...

⽬录结构json file内容

{

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

以上这篇Python遍历⽂件夹 处理json⽂件的⽅法就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- igat.cn 版权所有 赣ICP备2024042791号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务