Python遍历文件夹处理json文件的方法-创新互联
有两种做法: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()
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章标题:Python遍历文件夹处理json文件的方法-创新互联
URL地址:http://www.cqwzjz.cn/article/djppoi.html


咨询
建站咨询
