【YAML 】入门速学

基本语法

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)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值