62 lines
1.6 KiB
Python
62 lines
1.6 KiB
Python
#! /usr/bin/env python3
|
|
|
|
import yaml
|
|
import ruamel.yaml
|
|
|
|
def read_and_modify_one_block_of_yaml_data(filename = str,key = str,value = str):
|
|
with open(filename, 'r') as f:
|
|
data = yaml.safe_load(f)
|
|
data[f'{key}'] = f'{value}'
|
|
with open(filename, 'w') as file:
|
|
yaml.dump(data,file,sort_keys=False)
|
|
print('done!')
|
|
|
|
|
|
def read_modify_save_yaml_data(filename,index,key,value,write_file):
|
|
with open(filename,'r') as f:
|
|
data = yaml.safe_load_all(f)
|
|
loaded_data = list(data)
|
|
print(loaded_data)
|
|
loaded_data[index][f'{key}'].append(f'{value}')
|
|
with open(filename, 'w') as file:
|
|
yaml.dump_all(loaded_data,file, sort_keys=False)
|
|
print(loaded_data)
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
#read yaml
|
|
with open('/home/jonnybravo/Projekte/docker-compose/adguard-home/docker-compose.yml', 'r') as file:
|
|
prime_service = yaml.safe_load(file)
|
|
#print(prime_service)
|
|
print(prime_service["services"]["adguardhome"]["image"])
|
|
#write yaml
|
|
my_yaml = yaml.safe_load('''
|
|
---
|
|
age: 30
|
|
automobiles:
|
|
- brand: Honda
|
|
type: Odyssey
|
|
year: 2018
|
|
- brand: Toyota
|
|
type: Sienna
|
|
year: 2015
|
|
name: John
|
|
test:
|
|
- test1
|
|
- test2
|
|
''')
|
|
#parsing yaml
|
|
yaml = ruamel.yaml.YAML()
|
|
yaml.indent(sequence=4, offset=2)
|
|
#yaml.dump(foo, sys.stdout)
|
|
|
|
#print(pars_test)
|
|
#writing test_yaml
|
|
with open('test.yml', 'w') as file:
|
|
yaml.dump(my_yaml, file)
|
|
|
|
#example modify yaml
|
|
#read_and_modify_one_block_of_yaml_data(filename="test.yml", key="year", value="2021")
|
|
#read_modify_save_yaml_data('test.yml', 0, 'test', 'test3', "test2") |