Parsing YAML files in Python involves utilizing specific libraries to interpret and manipulate YAML data. One of the most widely used libraries for this task is PyYAML.
PyYAML, available via pip install pyyaml, provides a comprehensive set of functions specifically designed for YAML parsing. Its usage is straightforward:
import yaml with open("example.yaml") as stream: try: print(yaml.safe_load(stream)) except yaml.YAMLError as exc: print(exc)
Here, yaml.safe_load() reads and parses the YAML file, returning a Python data structure representing its contents. For security reasons, it's recommended to use safe_load() instead of the load() function to prevent potential arbitrary code execution.
While PyYAML is a widely adopted choice, there are other options available, such as ruamel.yaml, which supports the YAML 1.2 specification, and oyaml, which preserves the ordering of elements in YAML files.
以上是如何在Python中解析YAML檔?的詳細內容。更多資訊請關注PHP中文網其他相關文章!