Reading YAML file with Python results in AttributeError
I'm trying to make a script to back up a MySQL database. I have a config.yml
file:
DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'
Now I need to read this file. My Python code so far:
import yaml
config = yaml.load(open('config.yml'))
print(config.DB_NAME)
And here is the error that comes up:
file "conf.py", line 4, in <module>
print(config.DB_NAME)
AttributeError: 'str' object has no attribute 'DB_NAME'
Does anyone have an idea where I made a mistake?
python yaml
add a comment |
I'm trying to make a script to back up a MySQL database. I have a config.yml
file:
DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'
Now I need to read this file. My Python code so far:
import yaml
config = yaml.load(open('config.yml'))
print(config.DB_NAME)
And here is the error that comes up:
file "conf.py", line 4, in <module>
print(config.DB_NAME)
AttributeError: 'str' object has no attribute 'DB_NAME'
Does anyone have an idea where I made a mistake?
python yaml
2
Welcome to SO btw. The question may be simple, the formatting is good and all useful elements are here. Enjoy your stay, and don't forget to mark an answer as approved when your question is fully answered :)
– spectras
Feb 1 '17 at 8:44
1
You should not be usingyaml.load()
as it can be unsafe and from your question it looks like you don't have the experience to judge correctly if you are affected or not (use.safeload()
instead). Your code also has a problem if readingconfig.yml
throws an error (while parsing), in that case your file might not be closed properly. You should use thewith
statement
– Anthon
Feb 1 '17 at 11:32
add a comment |
I'm trying to make a script to back up a MySQL database. I have a config.yml
file:
DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'
Now I need to read this file. My Python code so far:
import yaml
config = yaml.load(open('config.yml'))
print(config.DB_NAME)
And here is the error that comes up:
file "conf.py", line 4, in <module>
print(config.DB_NAME)
AttributeError: 'str' object has no attribute 'DB_NAME'
Does anyone have an idea where I made a mistake?
python yaml
I'm trying to make a script to back up a MySQL database. I have a config.yml
file:
DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'
Now I need to read this file. My Python code so far:
import yaml
config = yaml.load(open('config.yml'))
print(config.DB_NAME)
And here is the error that comes up:
file "conf.py", line 4, in <module>
print(config.DB_NAME)
AttributeError: 'str' object has no attribute 'DB_NAME'
Does anyone have an idea where I made a mistake?
python yaml
python yaml
edited Jan 1 at 20:03


finefoot
2,78541835
2,78541835
asked Feb 1 '17 at 8:00
Yerlan YeszhanovYerlan Yeszhanov
1721115
1721115
2
Welcome to SO btw. The question may be simple, the formatting is good and all useful elements are here. Enjoy your stay, and don't forget to mark an answer as approved when your question is fully answered :)
– spectras
Feb 1 '17 at 8:44
1
You should not be usingyaml.load()
as it can be unsafe and from your question it looks like you don't have the experience to judge correctly if you are affected or not (use.safeload()
instead). Your code also has a problem if readingconfig.yml
throws an error (while parsing), in that case your file might not be closed properly. You should use thewith
statement
– Anthon
Feb 1 '17 at 11:32
add a comment |
2
Welcome to SO btw. The question may be simple, the formatting is good and all useful elements are here. Enjoy your stay, and don't forget to mark an answer as approved when your question is fully answered :)
– spectras
Feb 1 '17 at 8:44
1
You should not be usingyaml.load()
as it can be unsafe and from your question it looks like you don't have the experience to judge correctly if you are affected or not (use.safeload()
instead). Your code also has a problem if readingconfig.yml
throws an error (while parsing), in that case your file might not be closed properly. You should use thewith
statement
– Anthon
Feb 1 '17 at 11:32
2
2
Welcome to SO btw. The question may be simple, the formatting is good and all useful elements are here. Enjoy your stay, and don't forget to mark an answer as approved when your question is fully answered :)
– spectras
Feb 1 '17 at 8:44
Welcome to SO btw. The question may be simple, the formatting is good and all useful elements are here. Enjoy your stay, and don't forget to mark an answer as approved when your question is fully answered :)
– spectras
Feb 1 '17 at 8:44
1
1
You should not be using
yaml.load()
as it can be unsafe and from your question it looks like you don't have the experience to judge correctly if you are affected or not (use .safeload()
instead). Your code also has a problem if reading config.yml
throws an error (while parsing), in that case your file might not be closed properly. You should use the with
statement– Anthon
Feb 1 '17 at 11:32
You should not be using
yaml.load()
as it can be unsafe and from your question it looks like you don't have the experience to judge correctly if you are affected or not (use .safeload()
instead). Your code also has a problem if reading config.yml
throws an error (while parsing), in that case your file might not be closed properly. You should use the with
statement– Anthon
Feb 1 '17 at 11:32
add a comment |
3 Answers
3
active
oldest
votes
There are 2 issues:
- As others have said, yaml.load() loads associative arrays as mappings, so you need to use
config['DB_NAME']
. - The syntax in your config file is not correct: in YAML, keys are separated from values by a colon+space.
Should work if the file is formatted like this:
DB_HOST: 'localhost'
DB_USER: 'root'
DB_USER_PASSWORD: 'P@$$w0rd'
DB_NAME: 'moodle_data'
BACKUP_PATH: '/var/lib/mysql/moodle_data'
add a comment |
To backup your data base, you should be able to export it as a .sql
file. If you're using a specific interface, look for Export
.
Then, for Python's yaml parser.
DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'
is a key-value
thing (sorry, didn't find a better word for that one). In certain langage (such as PHP I think), they are converted to objects. In python though, they are converted to dicts (yaml parser does it, JSON parser too).
# access an object's attribute
my_obj.attribute = 'something cool'
my_obj.attribute # something cool
del my_obj.attribute
my_obj.attribute # error
# access a dict's key's value
my_dict = {}
my_dict['hello'] = 'world!'
my_dict['hello'] # world!
del my_dict['hello']
my_dict['hello'] # error
So, that's a really quick presentation of dicts, but that should you get you going (run help(dict)
, and/or have a look here you won't regret it)
In your case:
config['DB_NAME'] # moodle_data
“JSON compiler” does not really make sense as parsing a JSON document produces a data structure, not a program. I suppose you meant JSON parser, and more specifically, python's default json parser. Good point insisting on using the correct tool for db backup btw.
– spectras
Feb 1 '17 at 8:36
1
Whoops... Thanks, fixed it!
– math2001
Feb 1 '17 at 8:40
import yaml config=yaml.load(open('config.yml')) db=config['DB_NAME'] print db still TypeError comes up "string indices must be integers, not str"
– Yerlan Yeszhanov
Feb 1 '17 at 8:54
add a comment |
Try this:
import yaml
with open('config.yaml', 'r') as f:
doc = yaml.load(f)
To access "DB_NAME" you can use:
txt = doc["DB_NAME"]
print txt
it says TypeError: string indices must be integers, not str
– Yerlan Yeszhanov
Feb 1 '17 at 8:24
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41974628%2freading-yaml-file-with-python-results-in-attributeerror%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
There are 2 issues:
- As others have said, yaml.load() loads associative arrays as mappings, so you need to use
config['DB_NAME']
. - The syntax in your config file is not correct: in YAML, keys are separated from values by a colon+space.
Should work if the file is formatted like this:
DB_HOST: 'localhost'
DB_USER: 'root'
DB_USER_PASSWORD: 'P@$$w0rd'
DB_NAME: 'moodle_data'
BACKUP_PATH: '/var/lib/mysql/moodle_data'
add a comment |
There are 2 issues:
- As others have said, yaml.load() loads associative arrays as mappings, so you need to use
config['DB_NAME']
. - The syntax in your config file is not correct: in YAML, keys are separated from values by a colon+space.
Should work if the file is formatted like this:
DB_HOST: 'localhost'
DB_USER: 'root'
DB_USER_PASSWORD: 'P@$$w0rd'
DB_NAME: 'moodle_data'
BACKUP_PATH: '/var/lib/mysql/moodle_data'
add a comment |
There are 2 issues:
- As others have said, yaml.load() loads associative arrays as mappings, so you need to use
config['DB_NAME']
. - The syntax in your config file is not correct: in YAML, keys are separated from values by a colon+space.
Should work if the file is formatted like this:
DB_HOST: 'localhost'
DB_USER: 'root'
DB_USER_PASSWORD: 'P@$$w0rd'
DB_NAME: 'moodle_data'
BACKUP_PATH: '/var/lib/mysql/moodle_data'
There are 2 issues:
- As others have said, yaml.load() loads associative arrays as mappings, so you need to use
config['DB_NAME']
. - The syntax in your config file is not correct: in YAML, keys are separated from values by a colon+space.
Should work if the file is formatted like this:
DB_HOST: 'localhost'
DB_USER: 'root'
DB_USER_PASSWORD: 'P@$$w0rd'
DB_NAME: 'moodle_data'
BACKUP_PATH: '/var/lib/mysql/moodle_data'
answered Feb 1 '17 at 9:06


Roel SchroevenRoel Schroeven
85857
85857
add a comment |
add a comment |
To backup your data base, you should be able to export it as a .sql
file. If you're using a specific interface, look for Export
.
Then, for Python's yaml parser.
DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'
is a key-value
thing (sorry, didn't find a better word for that one). In certain langage (such as PHP I think), they are converted to objects. In python though, they are converted to dicts (yaml parser does it, JSON parser too).
# access an object's attribute
my_obj.attribute = 'something cool'
my_obj.attribute # something cool
del my_obj.attribute
my_obj.attribute # error
# access a dict's key's value
my_dict = {}
my_dict['hello'] = 'world!'
my_dict['hello'] # world!
del my_dict['hello']
my_dict['hello'] # error
So, that's a really quick presentation of dicts, but that should you get you going (run help(dict)
, and/or have a look here you won't regret it)
In your case:
config['DB_NAME'] # moodle_data
“JSON compiler” does not really make sense as parsing a JSON document produces a data structure, not a program. I suppose you meant JSON parser, and more specifically, python's default json parser. Good point insisting on using the correct tool for db backup btw.
– spectras
Feb 1 '17 at 8:36
1
Whoops... Thanks, fixed it!
– math2001
Feb 1 '17 at 8:40
import yaml config=yaml.load(open('config.yml')) db=config['DB_NAME'] print db still TypeError comes up "string indices must be integers, not str"
– Yerlan Yeszhanov
Feb 1 '17 at 8:54
add a comment |
To backup your data base, you should be able to export it as a .sql
file. If you're using a specific interface, look for Export
.
Then, for Python's yaml parser.
DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'
is a key-value
thing (sorry, didn't find a better word for that one). In certain langage (such as PHP I think), they are converted to objects. In python though, they are converted to dicts (yaml parser does it, JSON parser too).
# access an object's attribute
my_obj.attribute = 'something cool'
my_obj.attribute # something cool
del my_obj.attribute
my_obj.attribute # error
# access a dict's key's value
my_dict = {}
my_dict['hello'] = 'world!'
my_dict['hello'] # world!
del my_dict['hello']
my_dict['hello'] # error
So, that's a really quick presentation of dicts, but that should you get you going (run help(dict)
, and/or have a look here you won't regret it)
In your case:
config['DB_NAME'] # moodle_data
“JSON compiler” does not really make sense as parsing a JSON document produces a data structure, not a program. I suppose you meant JSON parser, and more specifically, python's default json parser. Good point insisting on using the correct tool for db backup btw.
– spectras
Feb 1 '17 at 8:36
1
Whoops... Thanks, fixed it!
– math2001
Feb 1 '17 at 8:40
import yaml config=yaml.load(open('config.yml')) db=config['DB_NAME'] print db still TypeError comes up "string indices must be integers, not str"
– Yerlan Yeszhanov
Feb 1 '17 at 8:54
add a comment |
To backup your data base, you should be able to export it as a .sql
file. If you're using a specific interface, look for Export
.
Then, for Python's yaml parser.
DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'
is a key-value
thing (sorry, didn't find a better word for that one). In certain langage (such as PHP I think), they are converted to objects. In python though, they are converted to dicts (yaml parser does it, JSON parser too).
# access an object's attribute
my_obj.attribute = 'something cool'
my_obj.attribute # something cool
del my_obj.attribute
my_obj.attribute # error
# access a dict's key's value
my_dict = {}
my_dict['hello'] = 'world!'
my_dict['hello'] # world!
del my_dict['hello']
my_dict['hello'] # error
So, that's a really quick presentation of dicts, but that should you get you going (run help(dict)
, and/or have a look here you won't regret it)
In your case:
config['DB_NAME'] # moodle_data
To backup your data base, you should be able to export it as a .sql
file. If you're using a specific interface, look for Export
.
Then, for Python's yaml parser.
DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'
is a key-value
thing (sorry, didn't find a better word for that one). In certain langage (such as PHP I think), they are converted to objects. In python though, they are converted to dicts (yaml parser does it, JSON parser too).
# access an object's attribute
my_obj.attribute = 'something cool'
my_obj.attribute # something cool
del my_obj.attribute
my_obj.attribute # error
# access a dict's key's value
my_dict = {}
my_dict['hello'] = 'world!'
my_dict['hello'] # world!
del my_dict['hello']
my_dict['hello'] # error
So, that's a really quick presentation of dicts, but that should you get you going (run help(dict)
, and/or have a look here you won't regret it)
In your case:
config['DB_NAME'] # moodle_data
edited Feb 1 '17 at 8:40
answered Feb 1 '17 at 8:26


math2001math2001
1,8471129
1,8471129
“JSON compiler” does not really make sense as parsing a JSON document produces a data structure, not a program. I suppose you meant JSON parser, and more specifically, python's default json parser. Good point insisting on using the correct tool for db backup btw.
– spectras
Feb 1 '17 at 8:36
1
Whoops... Thanks, fixed it!
– math2001
Feb 1 '17 at 8:40
import yaml config=yaml.load(open('config.yml')) db=config['DB_NAME'] print db still TypeError comes up "string indices must be integers, not str"
– Yerlan Yeszhanov
Feb 1 '17 at 8:54
add a comment |
“JSON compiler” does not really make sense as parsing a JSON document produces a data structure, not a program. I suppose you meant JSON parser, and more specifically, python's default json parser. Good point insisting on using the correct tool for db backup btw.
– spectras
Feb 1 '17 at 8:36
1
Whoops... Thanks, fixed it!
– math2001
Feb 1 '17 at 8:40
import yaml config=yaml.load(open('config.yml')) db=config['DB_NAME'] print db still TypeError comes up "string indices must be integers, not str"
– Yerlan Yeszhanov
Feb 1 '17 at 8:54
“JSON compiler” does not really make sense as parsing a JSON document produces a data structure, not a program. I suppose you meant JSON parser, and more specifically, python's default json parser. Good point insisting on using the correct tool for db backup btw.
– spectras
Feb 1 '17 at 8:36
“JSON compiler” does not really make sense as parsing a JSON document produces a data structure, not a program. I suppose you meant JSON parser, and more specifically, python's default json parser. Good point insisting on using the correct tool for db backup btw.
– spectras
Feb 1 '17 at 8:36
1
1
Whoops... Thanks, fixed it!
– math2001
Feb 1 '17 at 8:40
Whoops... Thanks, fixed it!
– math2001
Feb 1 '17 at 8:40
import yaml config=yaml.load(open('config.yml')) db=config['DB_NAME'] print db still TypeError comes up "string indices must be integers, not str"
– Yerlan Yeszhanov
Feb 1 '17 at 8:54
import yaml config=yaml.load(open('config.yml')) db=config['DB_NAME'] print db still TypeError comes up "string indices must be integers, not str"
– Yerlan Yeszhanov
Feb 1 '17 at 8:54
add a comment |
Try this:
import yaml
with open('config.yaml', 'r') as f:
doc = yaml.load(f)
To access "DB_NAME" you can use:
txt = doc["DB_NAME"]
print txt
it says TypeError: string indices must be integers, not str
– Yerlan Yeszhanov
Feb 1 '17 at 8:24
add a comment |
Try this:
import yaml
with open('config.yaml', 'r') as f:
doc = yaml.load(f)
To access "DB_NAME" you can use:
txt = doc["DB_NAME"]
print txt
it says TypeError: string indices must be integers, not str
– Yerlan Yeszhanov
Feb 1 '17 at 8:24
add a comment |
Try this:
import yaml
with open('config.yaml', 'r') as f:
doc = yaml.load(f)
To access "DB_NAME" you can use:
txt = doc["DB_NAME"]
print txt
Try this:
import yaml
with open('config.yaml', 'r') as f:
doc = yaml.load(f)
To access "DB_NAME" you can use:
txt = doc["DB_NAME"]
print txt
answered Feb 1 '17 at 8:08
Shivkumar kondiShivkumar kondi
2,86741540
2,86741540
it says TypeError: string indices must be integers, not str
– Yerlan Yeszhanov
Feb 1 '17 at 8:24
add a comment |
it says TypeError: string indices must be integers, not str
– Yerlan Yeszhanov
Feb 1 '17 at 8:24
it says TypeError: string indices must be integers, not str
– Yerlan Yeszhanov
Feb 1 '17 at 8:24
it says TypeError: string indices must be integers, not str
– Yerlan Yeszhanov
Feb 1 '17 at 8:24
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41974628%2freading-yaml-file-with-python-results-in-attributeerror%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Welcome to SO btw. The question may be simple, the formatting is good and all useful elements are here. Enjoy your stay, and don't forget to mark an answer as approved when your question is fully answered :)
– spectras
Feb 1 '17 at 8:44
1
You should not be using
yaml.load()
as it can be unsafe and from your question it looks like you don't have the experience to judge correctly if you are affected or not (use.safeload()
instead). Your code also has a problem if readingconfig.yml
throws an error (while parsing), in that case your file might not be closed properly. You should use thewith
statement– Anthon
Feb 1 '17 at 11:32