[英]How do I edit a yaml file using ruamel.yaml package, without changing the indentation of the file?
I am using the code proposed here by Anthon but it doesn't seem to work.我正在使用Anthon 在这里提出的代码,但它似乎不起作用。
YAML file: YAML 文件:
init_config: {}
instances:
- host: <IP> # update with IP
username: <username> # update with user name
password: <password> # update with password
Code:代码:
import ruamel.yaml
yaml = ruamel.yaml.YAML()
file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))
instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'
with open('output.yaml', 'w') as fp:
yaml.dump(config, fp)
Expected output:预期输出:
init_config: {}
instances:
- host: 1.2.3.4 # update with IP
username: Username # update with user name
password: Password # update with password
Output that I get:我得到的输出:
init_config: {}
instances:
- host: 1.2.3.4 # update with IP
username: Username # update with user name
password: Password # update with password
Am I doing something wrong, or is the example broken?我做错了什么,还是这个例子坏了? How can I get the expected output?我怎样才能得到预期的输出?
Somewhere in updating the old round_trip_dump
routine in version 4 of that answer to use the YAML()
, I forgot to change the arguments indent
and block_seq_indent
to a call to the .indent()
method, as shown in the last code section of that answer.在更新该答案版本 4 中旧的round_trip_dump
例程以使用YAML()
某个地方,我忘记将参数indent
和block_seq_indent
更改为对.indent()
方法的调用,如该答案的最后一个代码部分所示.
import sys
import ruamel.yaml
import ruamel.yaml
from ruamel.yaml import YAML
yaml=YAML()
file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))
instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'
yaml.indent(mapping=ind, sequence=ind, offset=bsi) # <<<< missing
yaml.dump(config, sys.stdout)
which gives:这使:
init_config: {}
instances:
- host: 1.2.3.4 # update with IP
username: Username # update with user name
password: Password # update with password
I normally make a single .ryd file when I answer on SO.当我回答 SO 时,我通常会制作一个 .ryd 文件。 That file has both text and code segments and when processed gets combined with the results of the code output in the form of an answer that I can paste in on SO.该文件具有文本和代码段,并且在处理时以答案的形式与代码输出的结果相结合,我可以将其粘贴到 SO 上。 That way there is never a discrepancy between code and output.这样,代码和输出之间永远不会有差异。
But that answer is from before I started using that, and I didn't make the .ryd file for the old answer when I updated it.但是这个答案是在我开始使用它之前的,我在更新它时没有为旧答案制作 .ryd 文件。 I should have...我应该...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.