提取函数以生成文件路径:def _file_paths(directory):
for root, dirs, filenames in os.walk(directory):
for filename in filenames:
file_path = os.path.join(root, filename)
if os.path.isfile(file_path):
yield file_path
统一异常处理:
^{pr2}$
提取用于处理文件类型的函数:def _handle_cfn(file_object):
file_contents = file_object.read()
if "AWSTemplateFormatVersion" in file_contents:
data = json.dumps(file_contents)
print(data)
def _handle_tf(file_object):
obj = hcl.load(file_oject)
data = json.dumps(obj)
print(data)
为文件扩展名不匹配时创建空处理程序:def _null_handler(file_object):
pass
将文件扩展名映射到处理程序:_extension_handlers = {'.json': _handle_cfn,
'.template': _handle_cfn,
'.yaml': _handle_cfn,
'.yml': _handle_cfn,
'.tf': _handle_tf}
组合起来:import os
import json
import click
import hcl
def file_handler(dir):
for file_path in _file_paths(dir):
base, extension = os.path.splitext(file_path)
handler = _extension_handlers.get(extension, _null_handler)
with open(file_path) as file_object:
with _translate_error(ValueError, SystemExit):
handler(file_object)
您可以进一步提取一个用于处理每个文件的函数:def _handle_file(file_path):
base, extension = os.path.splitext(file_path)
handler = _extension_handlers.get(extension, _null_handler)
with open(file_path) as file_object:
with _translate_error(ValueError, SystemExit):
handler(file_object)
那么您的主要功能是:def file_handler(dir):
for file_path in _file_paths(dir):
_handle_file(file_path)