Skip to content

Instantly share code, notes, and snippets.

@ipetropolsky
Created October 18, 2020 16:17
Show Gist options
  • Save ipetropolsky/6b763f54196e922a4f639a89fcd0efc8 to your computer and use it in GitHub Desktop.
Save ipetropolsky/6b763f54196e922a4f639a89fcd0efc8 to your computer and use it in GitHub Desktop.
Парсинг, изменение и сохранение yaml с помощью ruamel.yaml
# file comment
invoice: 34843
date: 2001-01-23
# Русский коммент
bill-to: &id001
given: Джон
family: Коннор
address:
lines: |
458 Walkman Dr.
Suite #292
city: Royal Oak # inline comment
state: MI
postal: 48046
# block comment
new item: '12312'
ship-to: *id001
product:
- sku: [BL394D, BUBU1245]
quantity: 4
# item comment
description: Basketball
price: 450.00
- sku: BL4438H
quantity: 1
description: 'Super Hoop'
price: 2392.00
- '12312'
tax: 251.42
total: 4443.52
comments: >
Late afternoon is best.
Backup contact is Nancy
Billsmer @ 338-4338.
flow sequence: [FlowEntryToken, 'FlowEntryToken', '12312']
flow mapping: {KeyToken: ValueToken}
# Обычный pyyaml не сохраняет переводы строк и комментарии
import ruamel.yaml
def update_yaml(source_path, dest_path=None, processor=None):
yaml = ruamel.yaml.YAML()
yaml.default_flow_style = False
yaml.preserve_quotes = True
yaml.indent(mapping=2, sequence=4, offset=2)
with open(source_path, 'r') as file:
data = yaml.load(file)
file.close()
processor(data)
if dest_path is not None:
with open(dest_path, 'w') as dest_file:
yaml.dump(data, dest_file)
dest_file.close()
return data, yaml
def processor(data):
data['bill-to']['new item'] = '12312' # :-/
data['flow sequence'].append('12312')
data['product'].append('12312') # :-/
data, yaml = update_yaml('source.yaml', 'result.yaml', processor=processor)
print(data)
# file comment
invoice: 34843
date : 2001-01-23
# Русский коммент
bill-to: &id001
given : Джон
family : Коннор
address:
lines: |
458 Walkman Dr.
Suite #292
city : Royal Oak # inline comment
state : MI
postal : 48046
# block comment
ship-to: *id001
product:
- sku : [BL394D, BUBU1245]
quantity : 4
# item comment
description : Basketball
price : 450.00
- sku : BL4438H
quantity : 1
description : 'Super Hoop'
price : 2392.00
tax : 251.42
total: 4443.52
comments: >
Late afternoon is best.
Backup contact is Nancy
Billsmer @ 338-4338.
flow sequence: [FlowEntryToken, 'FlowEntryToken']
flow mapping: {KeyToken: ValueToken}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment