python 之yaml库使用总结
import yaml
# 解析YAML内容
def parse_yaml(yaml_content):
try:
return yaml.safe_load(yaml_content)
except yaml.YAMLError as e:
print(e)
return None
# 读取YAML文件
def read_yaml_file(file_path):
try:
with open(file_path, 'r') as file:
return yaml.safe_load(file)
except yaml.YAMLError as e:
print(e)
return None
# 写入YAML文件
def write_yaml_file(data, file_path):
try:
with open(file_path, 'w') as file:
yaml.dump(data, file, default_flow_style=False)
except yaml.YAMLError as e:
print(e)
return False
return True
# 示例
yaml_content = """
a: 1
b:
c: 2
d: [3, 4]
"""
parsed_data = parse_yaml(yaml_content)
print(parsed_data) # 输出: {'a': 1, 'b': {'c': 2, 'd': [3, 4]}}
# 读取文件示例
file_path = 'example.yaml' # 假设存在一个example.yaml文件
data = read_yaml_file(file_path)
print(data)
# 写入文件示例
new_data = {'e': 5, 'f': {'g': 6, 'h': [7, 8]}}
success = write_yaml_file(new_data, file_path)
if success:
print(f'Data written to {file_path} successfully.')
这段代码提供了使用Python的yaml库来解析YAML内容、读取YAML文件和写入YAML文件的基本方法。它展示了如何安全地处理YAML内容,并在遇到错误时提供有用的反馈。
评论已关闭