【发布时间】:2018-01-08 00:59:57
【问题描述】:
我正在尝试编写一个 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 &&\
我做错了什么?
【问题讨论】:
-
显示您的完整代码。目前,您正在为
input_data[key]分配一些东西,然后转储data_loaded,这是我们以前从未见过的。在数据前面加上|-肯定是错误的,它不是内容的一部分。 -
@flyx,谢谢,添加到问题中