Python遍历文件夹处理json文件的方法-创新互联

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

创新互联建站服务紧随时代发展步伐,进行技术革新和技术进步,经过10余年的发展和积累,已经汇集了一批资深网站策划师、设计师、专业的网站实施团队以及高素质售后服务人员,并且完全形成了一套成熟的业务流程,能够完全依照客户要求对网站进行成都做网站、网站建设、外贸营销网站建设、建设、维护、更新和改版,实现客户网站对外宣传展示的首要目的,并为客户企业品牌互联网化提供全面的解决方案。

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

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文件的方法-创新互联
文章链接:http://pwwzsj.com/article/djppoi.html