-1

I need to write a yaml file in a format like:

abc:0 "def"

my current solution is to make a dict like:

{abc:'0 "def"'}

but if I use yaml.dump(dict,file) to write it, it will become:

abc: 0 "def" (there is a space after the colon, before the values.)

how can I remove the space after the colon?

=====================================================================

or the question could be:

if I make a dict like:

{abc:'"def"'}

then the output will be

abc: "def" 

then how can I add a '0' after the colon?

Thanks!

buran
  • 13,682
  • 10
  • 36
  • 61
Newoat
  • 21
  • 1
  • 1
    Does this answer your question? [Why does the YAML spec mandate a space after the colon?](https://stackoverflow.com/questions/42124227/why-does-the-yaml-spec-mandate-a-space-after-the-colon) – buran Dec 16 '20 at 14:37
  • thanks! I think so. Then I guess I can't output it as I wanted. :( – Newoat Dec 16 '20 at 14:54

1 Answers1

0

abc:0 "def" is indeed valid YAML. However, it gets loaded as a single scalar containing the string "abc:0 \"def\"". The colon is not interpreted as end of an implicit key because it is not followed by a space. Conversely, to produce this YAML, you would need to serialize the string:

import yaml, sys

yaml.dump("abc:0 \"def\"", sys.stdout)

This yields

abc:0 "def"
...

... is the document end marker. PyYAML always emits it if you serialize a single scalar. It doesn't change the YAML's meaning.

Now the real question is, is this what you want? A YAML file that is interpreted as single string? If you want this, why would you even use YAML – you could simply write the string to the file.

flyx
  • 35,506
  • 7
  • 89
  • 126