python3将文件的内容写入yaml

时间:2017-08-01 08:47:24

标签: python file yaml

我试图编写一个python3代码来迭代看起来像这样的YAML文件,例如:

my_yaml.yaml

input:
    program:
        filename: 01-02.c

查找01-02.c文件,读取并将其写回YAML文件,看起来像这样

my_yaml.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 &&\

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您不能仅通过预先|-

来设置输出格式
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)