python3将文件内容写入yam

2024-09-26 22:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个python3代码来迭代YAML文件,例如:

我的_亚马尔。亚马尔你知道吗

input:
    program:
        filename: 01-02.c

查找01-02.c文件,读取它并将其写回YAML文件,该文件如下所示

我的_亚马尔。亚马尔你知道吗

input:
    program: |-
        #include<stdlib.h>
        #include<stdio.h>

        int main(void)
        {
            int bobDylan = 50;
            int ummKulthum = 100;
            int janisJoplin = 10;
            int johnnyCash = 90;
            // duduTasa was an unused variable!
                                                                        // bobDylan | ummKulthum | janisJoplin | johnnyCash
                                                                        // --------   -----------   -------------   ---------------
            johnnyCash /= 3;                                            //    50    |     100     |       10      |        30
            bobDylan = ummKulthum + janisJoplin++ * 3;                  //   130    |     100     |       11      |        30
            bobDylan += --johnnyCash + janisJoplin + ummKulthum;        //    70    |     100     |       11      |       29

            printf("How many roads must a man walk down before you can call him a man?\n");
            printf("The answer my friend, is %d\n", bobDylan);
            return 0;
        }

下面是我如何读取YAML文件:

with open(file_path, 'r') as stream:
    try:
        data_loaded = yaml.load(stream)
    except yaml.YAMLError as exc:
        print('yaml loading error for ' + repr(file_path) + ' ' + repr(exc))
        return

return data_loaded

我把文件读得像这样:

program_content = open(filename_to_replace, 'r').read()
data_loaded['input'][key] = '|- ' + program_content

但当我回信时,用这个:

with open(file_path, 'w') as yml:
   yaml.dump(data_loaded, yml, default_flow_style=False)

最终结果如下:

input:
  program: "|- #include<stdio.h>\n#include<string.h>\n\n#define STR_LEN 20\n#define\
    \ LITTLE_A_CHAR 'a'\n#define LITTLE_Z_CHAR 'z'\n#define BIG_A_CHAR 'A'\n#define\
    \ BIG_Z_CHAR 'Z'\n\nvoid myFgets(char str[], int n);\n\nint main(void)\n{\n\t\
    char str[STR_LEN] = { 0 };\n\tchar smallStr[STR_LEN] = { 0 }, bigStr[STR_LEN]\
    \ = { 0 };\n\tint ind = 0, sInd = 0, bInd = 0;\n\n\tprintf(\"Enter a string with\
    \ upper and lower case letters: \");\n\tmyFgets(str, STR_LEN);\n\n\tfor (ind =\
    \ 0; ind < (int)strlen(str); ind++)\n\t{\n\t\tif (str[ind] >= LITTLE_A_CHAR &&\

我做错什么了?你知道吗


Tags: 文件inputlenincludeprogramintindchar
1条回答
网友
1楼 · 发布于 2024-09-26 22:09:21

您不能仅通过在|-前面加上前缀来设置输出格式:

data_loaded['input'][key] = '|- ' + program_content

应将以下内容添加到导入中:

from ruamel.yaml.scalarstring import PreservedScalarString
from ruamel.yaml import YAML

yaml = YAML()  

然后将该行替换为:

data_loaded['input'][key] = PreservedScalarString(program_content)

相关问题 更多 >

    热门问题