Search code examples
pythonpython-3.xyamlpythonanywhere

Yaml not working properly in Python3 version of pythonanywhere


Good day. I am trying to create a quick&dirty configuration file for my pythonanywhere code. I tried to use YAML, but the result is weird.

import os

import yaml

yaml_str = """Time_config:
    Tiempo_entre_avisos: 1
    Tiempo_entre_backups: 7
    Tiempo_entre_pushes: 30
Other_config:
    Morosos_treshold: 800
Mail_config:
    Comunication_mail: ''
    Backup_mail: ''
    Director_mail: []
"""

try:
    yaml_file = open("/BBDD/file.yml", 'w+')
except:
    print("FILE NOT FOUND")
else:
    print("PROCESSING FILE")
    yaml.dump(yaml_str, yaml_file, default_flow_style=False)
    a = yaml.dump(yaml_str, default_flow_style=False)
    print(a) #I make a print to debug
    yaml_file.close()

The code seems to work fairly well. However, the result seems corrupted. Both in the file and in the print it looks like this (including the "s):

"Time_config:\n    Tiempo_entre_avisos: 1\n    Tiempo_entre_backups: 7\n    Tiempo_entre_pushes:\  \ 30\nOther_config:\n    Morosos_treshold: 800\nMail_config:\n    Comunication_mail:\  \ ''\n    Backup_mail: ''\n    Director_mail: []\n"

If I copy and paste that string in the python console, yaml gives me the intended result, which is this one:

Time_config:
    Tiempo_entre_avisos: 1
    Tiempo_entre_backups: 7
    Tiempo_entre_pushes: 30
Other_config:
    Morosos_treshold: 800
Mail_config:
    Comunication_mail: ''
    Backup_mail: ''
    Director_mail: []

Why does this happen? Why I am not getting the result in the first shot? Why is it printing the newline symbol (\n) instead of inserting a new line? Why does it include the " symbols?


Solution

  • I think you should be loading the yaml from the string first, then continuing:

    # Everything before here is the same
        print("PROCESSING FILE")
        yaml_data = yaml.load(yaml_str)
        yaml.dump(yaml_data, yaml_file, default_flow_style=False)
        a = yaml.dump(yaml_data, default_flow_style=False)
        print(a) #I make a print to debug
        yaml_file.close()