0

How do you make Python set an str from a file? For example, my file would contain these pieces of text:

username=Eugene
password=eugene

How do I get Python to return this?

>>> print(username)
Eugene
>>> print(password)
eugene

Any help is deeply appreciated. Thanks!

2
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by 3e0jUn
0

You are trying to create a configuration file. Python has a module named ConfigParser (configparser in python 3) to handle this. A configurationf file
would look like this

# file myconfig.cfg

[user-info]         # <-- this is a section header (required for configparser)
username=Eugene
password=eugene

The code to read the file looks like

# file readconfig.py

import ConfigParser

config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(open("myconfig.cfg"))

print config.get("user-info", "username")
print config.get("user-info", "password")

""" my output -->
Eugene
eugene
"""

It's a good choice for configuration files.

Edited by Gribouillis

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.