I know there are a few questions about this on StackOverflow, but I couldn't find what I was looking for.
I'm using pyyaml to read (.load()) a .yml file, modify or add a key, and then write it (.dump()) again. The problem is that I want to keep the file format post-dump, but it changes.
For example, I edit the key en.test.index.few to say "Bye" instead of "Hello".
Python:
with open(path, "r", encoding = "utf-8") as yaml_file: self.dict = yaml.load(yaml_file) Then, after changing the key:
with open(path, "w", encoding = "utf-8") as yaml_file: dump = pyyaml.dump(self.dict, default_flow_style = False, allow_unicode = True, encoding = None) yaml_file.write( dump ) Yaml:
Before:
en: test: new: "Bye" index: few: "Hello" anothertest: "Something" After:
en: anothertest: Something test: index: few: Hello new: Bye Is there a way to keep the same format? For example the qoutes and order. Am I using the wrong tool for this?
I know maybe the original file it's not entirely correct, but I have no control over it (it's a Ruby-on-Rails i18n file).
Thank you very much.
yaml.dumphas adefault_styleargument. Usingdefault_style='"'will keep your string values in double quotes, but your keys and any other value types will also be wrapped in double quotes.yaml.loadgives you adict; its keys are unordered.yaml.dumpprobably outputs in whatever order the iteration goes.