pyyaml

Python3操作YAML文件

 ̄綄美尐妖づ 提交于 2020-04-29 14:10:07
数据及配置文件之争 数据及文件通常有三种类型: 配置文件型:如ini,conf,properties文件,适合存储简单变量和配置项,最多支持两层,不适合存储多层嵌套数据 表格矩阵型:如csv,excel等,适合于存储大量同类数据,不适合存储层级结构的数据 多层嵌套型:如XML,HTMl,JSON、YAML,TOML等,适合存储单条或少数多层嵌套数据,不适合存储大量数据 YAML兼容JSON格式,简洁,强大,灵活,可以很方便的构造层级数据并快速转为Python中的字典。 YAML简介 YAML(YAML Ain't Markup Language)即一种反标记(XML)语言。强调数据为中心,而非标记。YAML大小写敏感,使用缩进代表层级关系。 YAML中支持对象Object(对应Python中的字典), 数组Array(对应Python中的列表)以及常量(字符串、数字(int/float),true/false/null)。 相比于JSON格式,YAML免除了双引号,逗号,大括号,中括号等,(当然也支持原始的JSON格式),并且支持注释,类型转换,跨行,锚点,引用及插入等等。 基本格式 对象:使用 key: value 表示, 冒号后面有一个空格 ,也可以是使用 {key: value} (flow流格式)或 {"key": "value"} 表示 数组:使用 - value 表示,

yaml.dump adding unwanted newlines in multiline strings

邮差的信 提交于 2020-03-18 12:33:41
问题 I have a multiline string: >>> import credstash >>> d = credstash.getSecret('alex_test_key', region='ap-southeast-2') To see the raw data (first 162 characters): >>> credstash.getSecret('alex_test_key', region='ap-southeast-2')[0:162] u'-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEA6oySC+8/N9VNpk0gJS7Gk8vn9sYN7FhjpAQnoHRqTN/Oaiyx\nxk2AleP2vXpojA/DHldT1JO+o3j56AHD+yfNFFeYvgWKDY35g49HsZZhbyCEAB45\n' And: >>> print d[0:162] -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEA6oySC+8

Python使用PyYAML库读写yaml配置文件

别等时光非礼了梦想. 提交于 2020-02-29 03:15:57
一. yaml文件介绍 yaml是一个专门用来写配置文件的语言。 1. yaml文件规则 区分大小写; 使用缩进表示层级关系; 使用空格键缩进,而非Tab键缩进 缩进的空格数目不固定,只需要相同层级的元素左侧对齐; 文件中的字符串不需要使用引号标注,但若字符串包含有特殊字符则需用引号标注; 注释标识为# 2. yaml文件数据结构 对象:键值对的集合(简称 "映射或字典") 键值对用冒号 “:” 结构表示, 冒号与值之间需用空格分隔 数组:一组按序排列的值(简称 "序列或列表") 数组前加有 “-” 符号,符号与值之间需用空格分隔 纯量(scalars):单个的、不可再分的值(如:字符串、bool值、整数、浮点数、时间、日期、null等) None值可用null可 ~ 表示 二、python中读取yaml配置文件 1. 前提条件 python中读取yaml文件前需要安装pyyaml和导入yaml模块: 使用yaml需要安装的模块为pyyaml(pip3 install pyyaml); 导入的模块为yaml(import yaml) 2. 读取yaml文件数据 python通过open方式读取文件数据,再通过load函数将数据转化为列表或字典; import yaml import os def get_yaml_data(yaml_file): # 打开yaml文件 print(

How to safe_dump the dictionary and list into YAML?

ぃ、小莉子 提交于 2020-01-24 19:28:09
问题 I want the output as the YAML below: - item: Food_eat Food: itemId: 42536216 category: fruit moreInfo: - "organic" I have used the following code to print in the same order as above but output is coming not as expected. Code: import yaml yaml_result = [{'item': 'Food_eat', 'Food': {'foodNo': 42536216,'type': 'fruit','moreInfo': ['organic']}}] print(yaml.safe_dump(yaml_result)) print(yaml_test) Output: - Food: moreInfo: - organic category: fruit itemId: 42536216 item: Food_eat Not sure how to

How to append data to YAML file

安稳与你 提交于 2020-01-24 04:36:04
问题 I have a file *.yaml with contents as below: bugs_tree: bug_1: html_arch: filepath moved_by: user1 moved_date: '2018-01-30' sfx_id: '1' I want to add a new child element to this file under the node [bugs_tree] I have tried to do this as below: if __name__ == "__main__": new_yaml_data_dict = { 'bug_2': { 'sfx_id': '2', 'moved_by': 'user2', 'moved_date': '2018-01-30', 'html_arch': 'filepath' } } with open('bugs.yaml','r') as yamlfile: cur_yaml = yaml.load(yamlfile) cur_yaml.extend(new_yaml_data

How to preserve indenting in key-value when dumping yaml

社会主义新天地 提交于 2020-01-15 08:13:29
问题 How to preserve indenting in key-value when dumping yaml ? I am using ruamel yaml Code: in_str='''Pets: Cat: Tom Mouse: Jerry Dog: Scooby ''' import ruamel.yaml, sys results = ruamel.yaml.load(in_str, ruamel.yaml.RoundTripLoader, preserve_quotes=True) results['Pets']['Bird']='Tweety' ruamel.yaml.dump(results, sys.stdout, ruamel.yaml.RoundTripDumper, default_flow_style=True,indent=2, block_seq_indent=2) Output : Pets: Cat: Tom Mouse: Jerry Dog: Scooby Bird: Tweety Expected Output: Pets: Cat:

How to preserve indenting in key-value when dumping yaml

五迷三道 提交于 2020-01-15 08:12:58
问题 How to preserve indenting in key-value when dumping yaml ? I am using ruamel yaml Code: in_str='''Pets: Cat: Tom Mouse: Jerry Dog: Scooby ''' import ruamel.yaml, sys results = ruamel.yaml.load(in_str, ruamel.yaml.RoundTripLoader, preserve_quotes=True) results['Pets']['Bird']='Tweety' ruamel.yaml.dump(results, sys.stdout, ruamel.yaml.RoundTripDumper, default_flow_style=True,indent=2, block_seq_indent=2) Output : Pets: Cat: Tom Mouse: Jerry Dog: Scooby Bird: Tweety Expected Output: Pets: Cat:

python: how to add a new key and a value in yaml file

不问归期 提交于 2020-01-14 10:28:29
问题 I have the following YAML file. I need to update the YAML file with a new key-value pair using python. I am doing the following but, it gives me error: pod = mylib.load_yaml("net/pod.yaml") pod['spec']['nodeSelector']['key']='val' it gives error saying KeyError:'nodeSelector' spec: containers: - image: ceridwen/networking:v1 imagePullPolicy: Always name: networking readinessProbe: tcpSocket: port: 5000 initialDelaySeconds: 5 periodSeconds: 1 restartPolicy: Always I need to update it with a

Specifying styles for portions of a PyYAML dump

泪湿孤枕 提交于 2020-01-10 04:52:27
问题 I'm using YAML for a computer and human-editable and readable input format for a simulator. For human readability, some parts of the input are mostly amenable to block style, while flow style suits others better. The default for PyYAML is to use block style wherever there are nested maps or sequences, and flow style everywhere else. *default_flow_style* allows one to choose all-flow-style or all-block-style. But I'd like to output files more of the form bonds: - { strength: 2.0 } - ... tiles:

Logstash file input: registering json file grew but not taking data in some cases

牧云@^-^@ 提交于 2020-01-06 10:04:53
问题 My config file is shown below: input { file { codec => "json" path => "/home/data/*" sincedb_path => "/dev/null" } } output { elasticsearch{ protocol => "http" host => "localhost" index => "data" } } When I download a .json file to the data directory, logstash will not receive the data or output to elasticsearch unless I first open the file and save it in gedit. Running logstash with the -vvv flag shows no errors all I get when a file is put in that directory is _discover_file: /home/data/*: