python讀取配置檔案yaml

2022-08-02 05:27:10 字數 2979 閱讀 6297

yaml:一種非標記語言,可以簡單表達清單、列表等資料形態,檔案字尾為 .yml

1.大小寫敏感

2.使用縮排表示層級關係

3.縮排不允許使用tab,只允許空格,但是對空格數不要求

4.# 表示注釋

key: value  ":"和value之間應該有空格

# 字典 

name: test

age: 12

#

列表 [1,2 ,3]

-1-2

-3

#

字典巢狀字典, 'stud2': }

stud1:

name: test

age: 12stud2:

name: test2

age:12

#字典巢狀列表

list1:

-1-2

-3list2:

-4-5

-6 #

列表巢狀列表,[[1,2,3], [4,5,6]]

- -1

-2-3

- -4

-5-6

a.引號

字元可以用單引號或者雙引號或者不用,單引號會將字元內的特殊符號轉義。eg. 'test\ntest',輸出是test\ntest

雙引號不會轉義特殊符號

b.文字塊 使用|標註的文字內容縮排表示的塊,可以保留塊中已有的換行符【存疑】

name: | 

test

test

輸出果,會保留換行

name: | +

test

test

刪除文字塊末尾的換行

name: -

test

test

>將文字塊中的回車替換成空格

name: >

test

test   

輸出test test

c.引用

&表示複製資料的別名以及內容,*表示引用

name: &a test

age: *a

輸出age=test

d.存量

布林值: true、false或者true或者true

數字:12 整數

0b1010_0111 二進位制

.inf 空值,無窮大

浮點數1.2

1.2e+4 科學計數法

f.空值

null或者~表示

g.日期和時間

date:

- 2018-02-17 #日期必須使用iso 8601格式,即yyyy-mm-dd

datetime:

- 2018-02-17t15:02:31+08:00 #時間使用iso 8601格式,時間和日期之間使用t連線,最後使用+代表時區

h.強制型別轉換

單個感嘆號表示強制轉換資料型別,通常是自定義型別,雙嘆號是內建型別轉換。

age: !!str

dict1 = }

}

with open('

test_dict.yaml

', '

w', encoding='

utf-8

') as f:

yaml.dump(dict1, f)

def dump(data, stream=none, dumper=dumper, **kwds):

"""serialize a python object into a yaml stream.

if stream is none, return the produced string instead.

"""return dump_all([data], stream, dumper=dumper, **kwds)

def load(stream, loader=none):

"""parse the first yaml document in a stream

and produce the corresponding python object.

"""if loader is

none:

load_warning(

'load')

loader =fullloader

loader =loader(stream)

try:

return

loader.get_single_data()

finally

: loader.dispose()

**實現

def

read_dict_yaml():

with open(

'test_dict.yaml

', '

r', encoding='

utf-8

') as f:

print(yaml.load(f.read()))

錯誤和警告

yaml.load()如果引數loader使用預設值的話會報錯:yamlloadwarning: calling yaml.load() without loader=... is deprecated, as the default loader is unsafe. please read for full details.

官網解釋: 

pyyaml提供了safe_load函式,該函式可以載入yam的子集。

或者使用loader宣告載入器。

baseloader 基本載入器,載入最基本的yaml

safeloader 安全地載入yaml語言的子集,建議載入不信任的輸入

fullloader 載入完整的yaml語言,避免執行任意**(這是當前pyyaml 5.1在發出警告後呼叫的預設引導程式)

unsafeloder 也成為向後相容的loader【存疑】

Python 配置檔案讀取

python提供了configparser包來進行配置檔案讀取。api 所謂的sections就是乙個配置塊。下面是乙個配置檔案db.ini mongo db host 127.0.0.1 db port 27017 system timeout 2000 interval 2000 包含mongo...

python讀取配置檔案

在對pyqt的使用中,很多變數是需要靈活配置的,防止動輒需要修改程式。python提供了configparser模組 配置檔案片段如下 db 資料庫型別 db type mysql,oracle,highgo 片段如下 configfile component.ini cf configparser...

Python 讀取配置檔案

1 配置檔案db config.ini 2 python讀取配置檔案 import configparser 讀取配置檔案 建立乙個管理物件 conf configparser.configparser 配置檔案匯入管理物件,配置檔案內容載入到記憶體中 conf.read db config.ini...