PyYAML
Source code: https://github.com/yaml/pyyaml
install
# pip command line installation
pip install PyYAML
# Download the source code for installation
python setup.py install
Import
import yaml
Read yaml file
def read_yaml(yml_file, mode='r', encoding='utf-8'):
""" Read and convert the contents of yaml to Python objects
:param yml_file:
:param mode:
:param encoding:
:return:
"""
# safe_load_all() Open multiple documents
with open(yml_file, mode=mode, encoding=encoding) as y_file:
# .load is a non-recommended and unsafe encoding method
# content = yaml.load(y_file.read(), yaml.FullLoader)
# .safe_load safe encoding method
# If you don't trust the input stream, you should use:
return yaml.safe_load(y_file)
Write yaml file
def write_yaml(yaml_file, data, mode='w', encoding='utf-8', is_flush=True):
""" Converting Python objects to yaml
:param yaml_file:
:param data:
:param mode:
:param encoding:
:param is_flush:
:return:
"""
with open(yaml_file, mode=mode, encoding=encoding) as y_file:
# yaml.dump(data, stream=y_file)
# allow_unicode Solve the problem of writing messy code
yaml.safe_dump(data, stream=y_file, allow_unicode=True)
if is_flush:
y_file.flush()
Read More:
- [Solved] ERROR: Cannot uninstall ‘PyYAML‘. It is a distutils installed project and thus we cannot accurately
- An introduction to sys modules in Python and how packages are imported and used
- [solution] pyinnstaller package EXE file tutorial
- How to Fix Python reading large local file memory error
- [Solved] CONDA ENV create and run Error: F environment.yml under win10
- Error reading file by pandas pandas.errors.EmptyDataError: no columns to parse from file
- VScode: How to Solve Pylance Error (pip Library Files Installed)
- Python asynchronous execution library asyncio
- [Solved] ParserError: NULL byte detected. This byte cannot be processed in Python‘s native csv library
- [Solved] Pdfplumber Read PDF Sheet Error: AttributeError: function/symbol ‘ARC4_stream_init‘ not found in library
- Python netmiko library Cisco telnet switch automation
- Mac Upgrade pip Error OSError: [Errno 13] Permission denied: ‘/Library/Python/2.7/site-packages/pip-9.0.1-py2….
- [How to Solve] Reason: Incompatible library version
- Nltk Library Download error: [errno: 11004] getaddrinfo failed
- Decode PUP data Error when reading radar data [How to Solve]
- How to Solve Geopy library Error: Configurationerror Error
- FileNotFoundError: Could not find module ‘D:\Anaconda3\envs\labe\Library\bin\geos_c.dll‘ [Solved]
- [Solved] Pytorch Error: PytorchStreamReader failed reading zip archive failed finding central directory
- HDF5 library version mismatched error [How to Solve]
- [Solved] Pytorch Error: PytorchStreamReader failed reading zip archive failed finding central directory