Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import yaml
- import os
- class simple_yml:
- def __init__(self, file_name: str):
- self.file_name = file_name
- self.create_file_if_not_exists(self.file_name)
- def create_file_if_not_exists(self, file_name: str):
- if not os.path.exists(file_name):
- open(file_name, 'a').close()
- # read Yaml
- def read_yaml(self, file_name: str):
- with open(file_name, 'r') as yaml_file:
- yaml_dict = yaml.safe_load(yaml_file)
- return yaml_dict
- # Create key
- def create_key(self, file_name: str, section_name: str, key: str, value):
- data = {}
- # Read the existing data from the file
- with open(file_name, 'r') as stream:
- try:
- data = yaml.safe_load(stream)
- except yaml.YAMLError as exc:
- print(exc)
- # Add the new key-value pair
- if section_name:
- if section_name not in data:
- data[section_name] = {}
- data[section_name][key] = value
- else:
- data[key] = value
- # Write the updated data to the file
- with open(file_name, 'w') as stream:
- yaml.safe_dump(data, stream)
- # Overwrite key
- def overwrite_key(self, file_name: str, section_name: str, key: str, value):
- data = {}
- # Read the existing data from the file
- with open(file_name, 'r') as stream:
- try:
- data = yaml.safe_load(stream)
- except yaml.YAMLError as exc:
- print(exc)
- # Overwrite the key-value pair
- if section_name:
- if section_name not in data:
- data[section_name] = {}
- data[section_name][key] = value
- else:
- data[key] = value
- # Write the updated data to the file
- with open(file_name, 'w') as stream:
- yaml.safe_dump(data, stream)
- # Read Key
- def read_key(self, file_name: str, key: str, section: str = None):
- # Open the YAML file
- with open(file_name, 'r') as file:
- # Load the contents of the file as a dictionary
- data = yaml.safe_load(file)
- # If a section name is provided, get the value for that key in that section
- if section:
- return data[section][key]
- else:
- return data[key]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement