基本语法
1. 键值对
YAML中的基本单元是键值对,用冒号分隔:
name: John Doe
age: 30
2. 列表
列表使用短横线表示:
fruits:
- Apple
- Orange
- Banana
3. 嵌套结构
通过缩进表示嵌套结构:
person:
name: John Doe
age: 30
address:
street: 123 Main St
city: Anytown
zip: 12345
4. 字符串
字符串可以不使用引号,也可以使用单引号或双引号:
message: Hello, World!
single_quoted: 'Hello, World!'
double_quoted: "Hello, World!"
5. 多行字符串
多行字符串可以使用 |
保留换行,或者 >
折叠换行:
multiline_literal: |
This is a
multiline string.
multiline_folded: >
This is a
multiline string.
示例:复杂配置文件
以下是一个更复杂的示例,展示了如何使用YAML配置一个Web应用程序:
server:
host: "localhost"
port: 8080
database:
engine: "postgresql"
host: "db.example.com"
port: 5432
username: "dbuser"
password: "dbpass"
name: "mydatabase"
logging:
level: "DEBUG"
file: "/var/log/myapp.log"
features:
- "feature1"
- "feature2"
- "feature3"
email:
enabled: true
smtp_server: "smtp.example.com"
port: 587
from: "noreply@example.com"
to:
- "user1@example.com"
- "user2@example.com"
使用Python读取YAML文件
Python中可以使用 PyYAML
库来读取和写入YAML文件。以下是一个示例代码:
import yaml
# 读取YAML文件
with open('config.yaml', 'r') as file:
config = yaml.safe_load(file)
# 访问列表
features = config['features']
# 打印列表中的元素
for feature in features:
print(feature)
# 写入YAML文件
new_config = {
'server': {
'host': 'localhost',
'port': 9090
}
}
with open('new_config.yaml', 'w') as file:
yaml.safe_dump(new_config, file)