pyyaml and using quotes for strings only

后端 未结 2 1299
自闭症患者
自闭症患者 2021-01-17 09:51

I have the following YAML file:

---
my_vars:
  my_env: \"dev\"
  my_count: 3

When I read it with PyYAML and dump it again, I get the follow

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-17 10:30

    Right, so borrowing heavily from this answer, you can do something like this:

    import yaml
    
    # define a custom representer for strings
    def quoted_presenter(dumper, data):
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')
    
    yaml.add_representer(str, quoted_presenter)
    
    
    env_file = 'input.txt'
    with open(env_file) as f:
        env_dict = yaml.load(f)
        print yaml.dump(env_dict, default_flow_style=False)
    

    However, this just overloads it on all strings types in the dictionary so it'll quote the keys as well, not just the values.

    It prints:

    "my_vars":
      "my_count": 3
      "my_env": "dev"
    

    Is this what you want? Not sure what you mean by variable names, do you mean the keys?

提交回复
热议问题