ruamel在注释后创建空白行。

huangapple go评论95阅读模式
英文:

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)并将其去除,但未成功。

我正在使用:

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(&quot;someoutput.yaml&quot;).open(&#39;w&#39;))

huangapple
  • 本文由 发表于 2023年8月9日 14:48:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865236-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定