问题
If we want to alter the output of yaml.dump we can use tranform keyword argument. Documentation: https://yaml.readthedocs.io/en/latest/example.html
Here is the yaml data:
metadata:
name: name
alias: alias
it is stored in variable x.
x = 'metadata:\n name: name\n alias: alias\n'
def tr(s):
return s.replace('\n', '\n ') # Want 4 space at each new line
from ruamel.yaml import YAML
from ruamel.yaml.compat import StringIO
yaml = YAML(typ="safe")
yaml.default_flow_style = False
stream = StringIO()
obj = yaml.load(x)
yaml.dump(obj, stream, transform=tr)
print(stream.getvalue())
On running above python script, Got this error: TypeError: a bytes-like object is required, not 'str'
Expected output:
metadata:
name: name
alias: alias
Note: Another 4 spaces are added in each line
Version Details of setup:
Python: 3.7
ruamel.yaml: 0.15.88
回答1:
Well I got the answer now. Have some problems with StringIO only, because YAML() always sets the encoding to utf-8 (and allow_unicode = True) Changing to use io doesn't bring anything. If you want to write to a StringIO in 2.7 you'll have to disable the utf-8 encoding:
i.e.
yaml = YAML(typ="safe")
yaml.default_flow_style = False
stream = StringIO()
yaml.encoding = None
For more info visit this ticket : https://sourceforge.net/p/ruamel-yaml/tickets/271/
来源:https://stackoverflow.com/questions/61228863/transform-attribute-in-yaml-dump-is-not-working