<aside> <img src="/icons/reorder_gray.svg" alt="/icons/reorder_gray.svg" width="40px" /> Content
</aside>
Writing the Setup Configuration File — Python 3.11.4 documentation
Python config files are used to store configuration data for a program. One common file extension used for config files in Python is .cfg
. These files are usually simple text files that contain key-value pairs, with each pair representing a particular configuration setting.
Here is an example of a simple .cfg
file:
[Database]
host = localhost
port = 5432
database = mydatabase
username = myusername
password = mypassword
In Python, we can use the built-in configparser
module to read and write .cfg
files. Here is an example of how to read the values from the above config file:
import configparser
config = configparser.ConfigParser()
config.read('example.cfg')
host = config.get('Database', 'host')
port = config.getint('Database', 'port')
database = config.get('Database', 'database')
username = config.get('Database', 'username')
password = config.get('Database', 'password')
print(f"Connecting to {host}:{port}/{database} as {username}...")
In the above code, we first import the configparser
module and create a new instance of the ConfigParser
class. We then read in the contents of the example.cfg
file using the read
method.
We can then access the values in the config file using the get
method, which takes two arguments: the section name and the option name. We use getint
for the port
option since we know it is an integer.
Finally, we print out a message using the values we retrieved from the config file.
We can also use the set
method to update values in the config file, and the write
method to save any changes.
config.set('Database', 'password', 'newpassword')
with open('example.cfg', 'w') as configfile:
config.write(configfile)
In the above code, we update the password
option in the Database
section to a new value using the set
method. We then open the example.cfg
file in write mode and use the write
method to save the changes back to the file.
Using .cfg
files in Python can make it easy to store and manage configuration data for your programs.