我正在尝试编写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 &&\
我究竟做错了什么?
最佳答案
您不能仅在|-
前面设置输出格式:
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)
关于python - python3将文件内容写入yaml,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45433096/