在 Python 中,可以使用 PyYAML 库来读取 YAML 文件。以下是读取 YAML 文件的基本步骤:
安装 PyYAML
首先,确保安装了 PyYAML 库。如果尚未安装,可以通过以下命令安装:
pip install pyyaml
示例代码
以下是一个示例代码,展示如何读取 YAML 文件:
YAML 文件(示例 config.yaml)
database:
host: localhost
port: 3306
username: root
password: secret
features:
- login
- signup
- analytics
读取 YAML 文件的 Python 代码
import yaml
# 打开并读取 YAML 文件
with open('config.yaml', 'r', encoding='utf-8') as file:
config = yaml.safe_load(file)
# 打印读取的内容
print(config)
# 访问具体值
print("Database Host:", config['database']['host'])
print("Features:", config['features'])
输出结果
运行以上代码后,输出可能如下:
{'database': {'host': 'localhost', 'port': 3306, 'username': 'root', 'password': 'secret'}, 'features': ['login', 'signup', 'analytics']}
Database Host: localhost
Features: ['login', 'signup', 'analytics']
注意事项
- 使用
yaml.safe_load:safe_load是读取 YAML 文件的推荐方法,它会限制潜在危险的操作。 - 文件路径:确保提供正确的文件路径。如果文件不在当前目录,可以使用绝对路径或相对路径。
- 处理异常:在读取文件时可以添加异常处理,避免文件不存在或内容格式错误时导致程序崩溃。
try:
with open('config.yaml', 'r', encoding='utf-8') as file:
config = yaml.safe_load(file)
except FileNotFoundError:
print("YAML 文件未找到。")
except yaml.YAMLError as e:
print("YAML 文件格式错误:", e)

2965

被折叠的 条评论
为什么被折叠?



