python对yaml文件操作的常用方法整理。
import os
import yaml
# 从yaml文件中读取信息
def load_yaml(path):
data = ""
try:
file = open(path, 'r', encoding='utf-8')
data = yaml.load(file, Loader=yaml.FullLoader)
file.close()
except FileNotFoundError:
print("文件读取失败,原因:未找到该文件!")
except IOError as e:
print("文件操作出错", e)
finally:
return data
# 往yaml文件中写入信息(重新写入)
def write_yaml_w(path, data):
try:
file = open(path, 'w', encoding='utf-8')
yaml.dump(data, file, allow_unicode=True)
file.close()
except IOError as e:
print("文件操作出错", e)
# 往yaml文件中写入信息(追加写入)
def write_yaml_a(path, data):
try:
file = open(path, 'a', encoding='utf-8')
yaml.dump(data, file, allow_unicode=True)
file.close()
except IOError as e:
print("文件操作出错", e)
# 更新yaml文件中的信息,若文件不存在或文件为空则新建该文件,将该字段数据写入到文件中
def update_yaml(path, key, value):
try:
# 判断该文件是否存在
if os.access(path, os.F_OK):
first_data = load_yaml(path)
# 判断文件是否为空
if first_data:
first_data[key] = value
write_yaml_w(path, first_data)
else:
write_yaml_a(path, {key: value})
else:
write_yaml_a(path, {key: value})
except IOError as e:
print("文件操作出错", e)