Let's say I have the following yaml file and the value in the 4th row should be None
. How can I convert the string 'None'
to None
?
CREDENTIALS:
USERNAME: 'USERNAME'
PASSWORD: 'PASSWORD'
LOG_FILE_PATH: None <----------
I already have this:
config = yaml.safe_load(open(config_path, "r"))
username, password, log_file_path = (config['CREDENTIALS']['USERNAME'],
config['CREDENTIALS']['PASSWORD'],
config['LOG_FILE_PATH'])
I would like to know if there is a pythonic way to do this, instead of simply doing:
if log_file_path == 'None':
log_file_path = None
The None
value in your YAML file is not really kosher YAML since YAML it uses absence of a value to represent None. So if you just used proper YAML your troubles would be over:
In [7]: yaml.load("""
...: CREDENTIALS:
...: USERNAME: 'USERNAME'
...: PASSWORD: 'PASSWORD'
...: LOG_FILE_PATH:
...: """)
Out[7]:
{'CREDENTIALS': {'PASSWORD': 'PASSWORD', 'USERNAME': 'USERNAME'},
'LOG_FILE_PATH': None}
Notice how it read the absence of the LOG_FILE_PATH
as None
rather than 'None'
.
Later edit: Other values which also work are: null
, Null
and NULL
as per: https://yaml.org/type/null.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With