How can i output empty value in yythl python file

I am writing a yaml file like this

with open(fname, "w") as f:
     yaml.safe_dump({'allow':'', 'deny': ''}, f,
                    default_flow_style=False, width=50, indent=4)

      

Output:

allow: ''

      

I want to output as

allow:

      

How can i do this?

+3


source to share


4 answers


If you download YAML SRC

allow:

      

in Python you get None

assigned to a key allow

, this is the correct behavior.

If you are using ruamel.yaml ( the author of which I am) and RoundTripDumper

, None

being written as you want (which is IMO the most readable, though not explicit):

import ruamel.yaml

print ruamel.yaml.dump(dict(allow=None), Dumper=ruamel.yaml.RoundTripDumper)

      

I will give you:



allow:

      

You can also correctly back and forth this:

import ruamel.yaml

yaml_src = """
allow:
key2: Hello  # some test

"""

data = ruamel.yaml.load(yaml_src, ruamel.yaml.RoundTripLoader)
print('#### 1')
print(data['allow'])
print('#### 2')
print(ruamel.yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper))

print('#### 3')

print(type(data))

      

get as output:

#### 1
None
#### 2
allow:
key2: Hello  # some test


#### 3
<class 'ruamel.yaml.comments.CommentedMap'>

      

The above data

are a subclass of orderdict, which is needed to keep track of the style of the input stream, handle comments attached to lines, order of keys, etc.
Such a subclass can be created on the fly, but it is usually easier to start with some readable and well-formatted YAML code (possibly already saved to disk) and then update / expand the values.

+3


source


from yaml import SafeDumper
import yaml

data = {'deny': None, 'allow': None}

SafeDumper.add_representer(
    type(None),
    lambda dumper, value: dumper.represent_scalar(u'tag:yaml.org,2002:null', '')
  )

with open('./yadayada.yaml', 'w') as output:
  yaml.safe_dump(data, output, default_flow_style=False)

      

There is a way to do this inline in python yaml itself. The above code will create a file containing:



allow:
deny:

      

+3


source


Using replace, it looks simple:

import yaml

fname = 'test.yaml'
with open(fname, "w") as f:
    yaml_str = yaml.safe_dump({'allow':'', 'deny': ''},
                            default_flow_style=False,
                            width=50, 
                            indent=4).replace(r"''", '')
    f.write(yaml_str)

      

Is there a reason you want to avoid replace

?

There is a disadvantage that reloading the yaml file does not reproduce your input:

>>> print yaml.safe_load(open(fname))
{'deny': None, 'allow': None}

      

+1


source


To make the type None

read from python use null

in yaml

YAML file test.yml

like this

foo: null
bar: null

      

will be read by python as

import yaml
test = yaml.load(open('./test.yml'))
print(test)

foo: None
bar: None

      

0


source







All Articles