pyyaml: dumping without tags

前端 未结 5 1988
囚心锁ツ
囚心锁ツ 2021-01-30 19:45

I have

>>> import yaml
>>> yaml.dump(u\'abc\')
\"!!python/unicode \'abc\'\\n\"

But I want

>>> import         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 20:22

    little addition to interjay's excellent answer, you can keep your unicode on a reload if you take care of your file encodings.

    # -*- coding: utf-8 -*-
    import yaml
    import codecs
    
    data = dict(key = u"abcç\U0001F511")
    
    fn = "test2.yaml"
    with codecs.open(fn, "w", encoding="utf-8") as fo:
        yaml.safe_dump(data, fo)
    
    with codecs.open(fn, encoding="utf-8") as fi:
        data2 = yaml.safe_load(fi)
    
    print ("data2:", data2, "type(data.key):", type(data2.get("key")) )
    
    print data2.get("key")
    

    test2.yaml contents in my editor:

    {key: "abc\xE7\uD83D\uDD11"}

    print outputs:

    ('data2:', {'key': u'abc\xe7\U0001f511'}, 'type(data.key):', ) abcç

提交回复
热议问题