Python 寫入 yaml 檔案

本篇介紹如何用 Python 寫入 yaml 檔案,yaml 檔案格式是常用設定檔格式,以下將示範如何用 python 搭配 yaml 套件的 yaml.dump() 來寫入 yaml 檔案。

PyPI:https://pypi.org/project/PyYAML/
Github:https://github.com/yaml/pyyaml/

安裝方式

透過 pip 安裝 pyyaml,注意在程式裡是 import yaml

1
pip install pyyaml

寫入 yaml 檔案

以下示範寫入 yaml 檔案,首先要準備好資料存放在字典 dict 裡,之後在使用 yaml.dump() 寫入檔案,
程式碼如下:

python3-yaml-write.py
1
2
3
4
5
6
7
8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import yaml

d = {'name':'Amy', 'age':'20', 'languages':['English', 'French']}

with open('output.yaml', 'w') as f:
yaml.dump(d, f)

輸出的 output.yaml 如下,

output.yaml
1
2
3
age: '20'
languages: [English, French]
name: Amy

下一篇介紹 讀取 yaml 檔案

其他參考
PyYAML Documentation
https://pyyaml.org/wiki/PyYAMLDocumentation

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python 寫檔,寫入 txt 文字檔
Python 讀取 csv 檔案
Python 寫入 csv 檔案
Python 字串分割 split
Python 取代字元或取代字串 replace
Python 讓程式 sleep 延遲暫停時間
Python 產生 random 隨機不重複的數字 list
Python PyAutoGUI 使用教學
Python OpenCV resize 圖片縮放