英文:
ruamel creating empty blank lines after comment
问题
我正在努力使用ruamel来进行YAML文件的往返解析。以下是一个示例YAML文件input.yaml:
##### Header comment ####
key: #comment1
key2: val2
以下是Python代码:
from pathlib import Path
import ruamel.yaml
input = Path("input.yaml")
yaml = ruamel.yaml.YAML()
data = yaml.load(input)
yaml.dump(data, Path("someoutput.yaml"))
这将创建一个输出文件,在每个注释后面都有一个空白行:
##### Header comment ####
key: #comment1
key2: val2
我尝试递归地遍历每个注释(ca.comment)并将其去除,但没有成功。
我查阅了多个问题,但最接近的是这个问题:https://stackoverflow.com/questions/42172399/modifying-yaml-using-ruamel-yaml-adds-extra-new-linesw。然而,在这个问题中,注释本身有一个换行符,所以与我的问题无关。
我正在使用以下版本:
ruamel.yaml==0.17.32
Python 3.9
Windows
英文:
I'm struggling with doing a roundtrip parsing of a YAML file using ruamel.
Below is an example YAML file, input.yaml:
##### Header comment ####
key: #comment1
key2: val2
Below is the python code
from pathlib import Path
import ruamel.yaml
input = Path("input.yaml")
yaml = ruamel.yaml.YAML()
data = yaml.load(input)
yaml.dump(data,Path("someoutput.yaml"))
This creates an output file with blank newline after each comment
##### Header comment ####
key: #comment1
key2: val2
I tried recursively going through each comment (ca.comment) and stripping it but was not successful in that
I've gone through multiple questions but the closest I could found was
<https://stackoverflow.com/questions/42172399/modifying-yaml-using-ruamel-yaml-adds-extra-new-linesw>. However in this question the comment itself has a newline so not related to my problem
I'm using:
ruamel.yaml==0.17.32
python 3.9
Windows
答案1
得分: 1
当将pathlib.Path实例作为参数传递给YAML().load()时,该文件将以rb模式打开,并且\r\n结尾的处理应该由扫描器完成。
看起来这个方法没有正常工作,所以我建议尝试以下方法:
data = yaml.load(input.open())
和/或者:
yaml.dump(data,Path("someoutput.yaml").open('w'))
英文:
When handed a pathlib.Path instance as parameter to YAML().load() this file will be opened rb, and the processing of \r\n ending should be done by the scanner.
It looks like that doesn't work correctly, so I recommend trying:
data = yaml.load(input.open())
and/or:
yaml.dump(data,Path("someoutput.yaml").open('w'))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论