首页 > 解决方案 > 如何更改 YAML 文件中的一行?

问题描述

我有一堆 YAML 文件,每个文件都有一行代码需要更改。我正在尝试使用 Python 将其自动化,最好的方法是什么?

现在我有一个文件列表,我计划打开每个文件并找到需要更改的行然后替换它。

这可能吗?我似乎无法弄清楚如何更换线路。我知道确切的行号,有帮助吗?

标签: pythonyaml

解决方案


由于您知道确切的行号,这很容易 - 如果您确切知道需要用什么替换文件,那么文件是否是 YAML 甚至都没有关系。

我在这里假设所有需要更改行的文件都在同一个目录中,没有其他 YAML 文件。如果不是这种情况,那么程序当然需要微调。

import os
line_number = 47  # Whatever the line number you're trying to replace is
replacement_line = "Whatever string you're replacing this line with"

items = os.listdir(".")  # Gets all the files & directories in the folder containing the script

for file_name in items:  # For each of these files and directories,
    if file_name.lower().endswith(".yaml"):  # check if the file is a YAML. If it is:
        with open(file_name, "w") as file:  # Safely open the file
            data = file.read()  # Read its contents
            data[line_number] = replacement_line  # Replace the line
            file.write(data)  # And save the file

请注意,如果您的文件是 .yml 而不是 .yaml,那么您必须在代码中进行更改。此外,如果您的文件太大,这可能会导致每个文件都加载到内存中时出现问题。

如果这对您不起作用,那么互联网上还有其他解决方案,包括 Stack Overflow!


推荐阅读