Hướng dẫn how do i view a yaml file in python? - làm cách nào để xem tệp yaml trong python?

Tôi đã tạo ra kịch bản của riêng tôi cho việc này. Hãy thoải mái sử dụng nó, miễn là bạn giữ quy kết. Tập lệnh có thể phân tích YAML từ một tệp [hàm load], phân tích cú pháp YAML từ chuỗi [hàm loads] và chuyển đổi từ điển thành yaml [hàm dumps]. Nó tôn trọng tất cả các loại biến.

# © didlly AGPL-3.0 License - github.com/didlly

def is_float[string: str] -> bool:
    try:
        float[string]
        return True
    except ValueError:
        return False


def is_integer[string: str] -> bool:
    try:
        int[string]
        return True
    except ValueError:
        return False


def load[path: str] -> dict:
    with open[path, "r"] as yaml:
        levels = []
        data = {}
        indentation_str = ""

        for line in yaml.readlines[]:
            if line.replace[line.lstrip[], ""] != "" and indentation_str == "":
                indentation_str = line.replace[line.lstrip[], ""].rstrip["\n"]
            if line.strip[] == "":
                continue
            elif line.rstrip[][-1] == ":":
                key = line.strip[][:-1]
                quoteless = [
                    is_float[key]
                    or is_integer[key]
                    or key == "True"
                    or key == "False"
                    or ["[" in key and "]" in key]
                ]

                if len[line.replace[line.strip[], ""]] // 2 < len[levels]:
                    if quoteless:
                        levels[len[line.replace[line.strip[], ""]] // 2] = f"[{key}]"
                    else:
                        levels[len[line.replace[line.strip[], ""]] // 2] = f"['{key}']"
                else:
                    if quoteless:
                        levels.append[f"[{line.strip[][:-1]}]"]
                    else:
                        levels.append[f"['{line.strip[][:-1]}']"]
                if quoteless:
                    exec[
                        f"data{''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}[{key}]"
                        + " = {}"
                    ]
                else:
                    exec[
                        f"data{''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}['{key}']"
                        + " = {}"
                    ]

                continue

            key = line.split[":"][0].strip[]
            value = ":".join[line.split[":"][1:]].strip[]

            if [
                is_float[value]
                or is_integer[value]
                or value == "True"
                or value == "False"
                or ["[" in value and "]" in value]
            ]:
                if [
                    is_float[key]
                    or is_integer[key]
                    or key == "True"
                    or key == "False"
                    or ["[" in key and "]" in key]
                ]:
                    exec[
                        f"data{'' if line == line.strip[] else ''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}[{key}] = {value}"
                    ]
                else:
                    exec[
                        f"data{'' if line == line.strip[] else ''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}['{key}'] = {value}"
                    ]
            else:
                if [
                    is_float[key]
                    or is_integer[key]
                    or key == "True"
                    or key == "False"
                    or ["[" in key and "]" in key]
                ]:
                    exec[
                        f"data{'' if line == line.strip[] else ''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}[{key}] = '{value}'"
                    ]
                else:
                    exec[
                        f"data{'' if line == line.strip[] else ''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}['{key}'] = '{value}'"
                    ]
    return data


def loads[yaml: str] -> dict:
    levels = []
    data = {}
    indentation_str = ""

    for line in yaml.split["\n"]:
        if line.replace[line.lstrip[], ""] != "" and indentation_str == "":
            indentation_str = line.replace[line.lstrip[], ""]
        if line.strip[] == "":
            continue
        elif line.rstrip[][-1] == ":":
            key = line.strip[][:-1]
            quoteless = [
                is_float[key]
                or is_integer[key]
                or key == "True"
                or key == "False"
                or ["[" in key and "]" in key]
            ]

            if len[line.replace[line.strip[], ""]] // 2 < len[levels]:
                if quoteless:
                    levels[len[line.replace[line.strip[], ""]] // 2] = f"[{key}]"
                else:
                    levels[len[line.replace[line.strip[], ""]] // 2] = f"['{key}']"
            else:
                if quoteless:
                    levels.append[f"[{line.strip[][:-1]}]"]
                else:
                    levels.append[f"['{line.strip[][:-1]}']"]
            if quoteless:
                exec[
                    f"data{''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}[{key}]"
                    + " = {}"
                ]
            else:
                exec[
                    f"data{''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}['{key}']"
                    + " = {}"
                ]

            continue

        key = line.split[":"][0].strip[]
        value = ":".join[line.split[":"][1:]].strip[]

        if [
            is_float[value]
            or is_integer[value]
            or value == "True"
            or value == "False"
            or ["[" in value and "]" in value]
        ]:
            if [
                is_float[key]
                or is_integer[key]
                or key == "True"
                or key == "False"
                or ["[" in key and "]" in key]
            ]:
                exec[
                    f"data{'' if line == line.strip[] else ''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}[{key}] = {value}"
                ]
            else:
                exec[
                    f"data{'' if line == line.strip[] else ''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}['{key}'] = {value}"
                ]
        else:
            if [
                is_float[key]
                or is_integer[key]
                or key == "True"
                or key == "False"
                or ["[" in key and "]" in key]
            ]:
                exec[
                    f"data{'' if line == line.strip[] else ''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}[{key}] = '{value}'"
                ]
            else:
                exec[
                    f"data{'' if line == line.strip[] else ''.join[str[i] for i in levels[:line.replace[line.lstrip[], ''].count[indentation_str] if indentation_str != '' else 0]]}['{key}'] = '{value}'"
                ]

    return data


def dumps[yaml: dict, indent=""] -> str:
    """A procedure which converts the dictionary passed to the procedure into it's yaml equivalent.

    Args:
        yaml [dict]: The dictionary to be converted.

    Returns:
        data [str]: The dictionary in yaml form.
    """

    data = ""

    for key in yaml.keys[]:
        if type[yaml[key]] == dict:
            data += f"\n{indent}{key}:\n"
            data += dumps[yaml[key], f"{indent}  "]
        else:
            data += f"{indent}{key}: {yaml[key]}\n"

    return data


print[load["config.yml"]]

Thí dụ

config.yml

level 0 value: 0

level 1:
  level 1 value: 1
  level 2:
    level 2 value: 2

level 1 2:
  level 1 2 value: 1 2
  level 2 2:
    level 2 2 value: 2 2

Đầu ra

{'level 0 value': 0, 'level 1': {'level 1 value': 1, 'level 2': {'level 2 value': 2}}, 'level 1 2': {'level 1 2 value': '1 2', 'level 2 2': {'level 2 2 value': 2 2}}}

Làm cách nào để đọc tệp cấu hình yaml trong Python?

Đọc khóa từ tệp cấu hình YAML Chúng ta có thể đọc dữ liệu bằng YAML. Phương thức LOAD [] lấy con trỏ tệp và trình tải làm tham số. Fullloader xử lý việc chuyển đổi từ các giá trị vô hướng YAML sang từ điển Python. Chỉ mục [0] được sử dụng để chọn thẻ chúng tôi muốn đọc.using yaml. load[] method which takes file pointer and Loader as parameters. FullLoader handles the conversion from YAML scalar values to the Python dictionary. The index [0] is used to select the tag we want to read.

Làm cách nào để đọc tệp yaml?

YAML là ngôn ngữ tuần tự hóa dữ liệu có thể tiêu hóa thường được sử dụng để tạo các tệp cấu hình với bất kỳ ngôn ngữ lập trình nào.Được thiết kế cho sự tương tác của con người, YAML là một superset nghiêm ngặt của JSON, một ngôn ngữ tuần tự hóa dữ liệu khác.Nhưng bởi vì đó là một siêu sao nghiêm ngặt, nó có thể làm mọi thứ mà JSON có thể và hơn thế nữa.. Designed for human interaction, YAML is a strict superset of JSON, another data serialization language. But because it's a strict superset, it can do everything that JSON can and more.

Làm cách nào để đọc và cập nhật tệp yaml trong Python?

Cài đặt và nhập pyyaml..
$ Pip Cài đặt Pyyaml.$ Pip Cài đặt Pyyaml.Trên một số hệ thống bạn cần sử dụng PIP3:.
$ PIP3 Cài đặt pyyaml.$ PIP3 Cài đặt pyyaml.Để sử dụng pyyaml trong tập lệnh của bạn, hãy nhập mô -đun như sau.....
nhập khẩu yaml.nhập khẩu yaml.Đọc và phân tích một tệp yaml với Python ..

Làm thế nào để bạn đọc và ghi vào các tệp yaml trong python?

Viết từ điển vào tệp yaml trong Python..
Tải mô -đun YAML vào tệp Python ..
Tuyên bố một từ điển các đối tượng có dữ liệu ..
Mở tệp để ghi dữ liệu ..
Phương thức kết xuất mô -đun YAML ghi dữ liệu vào một tệp ..

Bài Viết Liên Quan

Chủ Đề