Search code examples
python-3.xpyyaml

PyYAML can't load from file but can write


I'm having an issue with PyYAML and I'm not sure if I'm doing anything wrong. This is the code:

import yaml
open("a", "w+")
with open("a", "r+") as f:
    yaml.dump({'foo':'bar'}, f)
    print(yaml.load(f))

When I look in the directory file a is there, and opening it in Notepad shows me this: {foo: bar}

However, print(yaml.load(f)) outputs None to the console

I have a feeling it has to do with the file being already open and/or the mode I'm using to open a file, because I've gotten it to work a grand total of 1 time when I was messing around, and when I repeated the EXACT SAME OPERATION it did not work, again, printing None


Solution

  • First of all your open("a", "w+") doesn't do anything useful.

    But more importantly once you do yaml.dump(..., f) the file pointer is at the end of the file. Invoking yaml.load(f) at that point will read from the end position of the file, with nothing following that position in that file.

    You can do f.seek(0) at the point, and then things should work.

    From your example it is not clear though why you would read and write from the same opened file, YAML is not good at updating files, so IMO you should always have a file close after dumping.

    As documented yaml.load() can be unsafe, and there is seldom need to use it. Use yaml.safe_load() instead.

    import yaml
    
    with open("a", "w") as f:
        yaml.safe_dump({'foo':'bar'}, f)
    with open("a") as f:
        print(yaml.safe_load(f))