When you start writing Python applications, you usually need a way to configure the settings of your application, such as database connection information, API keys, etc. Using configuration files is a common approach, while INI files are a simple and common configuration file format. In this article, I will explain how to set up and read configuration files in INI format using Python.
Create a file
First, we need to create an INI format configuration file. We will use the following structure as an example:
[database] host = localhost port = 5432 username = myusername password = mypassword [api] key = myapikey url =
In this example, we have two parts:[database]
and[api]
, each section is the relevant key-value pairs.
Setting up files
Let's see how to set up files in Python. We will use Python's built-in modulesconfigparser
To achieve this.
import configparser def create_config(): config = () # Set the database part config['database'] = { 'host': 'localhost', 'port': '5432', 'username': 'myusername', 'password': 'mypassword' } # Set the API section config['api'] = { 'key': 'myapikey', 'url': '' } # Write to file with open('', 'w') as configfile: (configfile) create_config()
This code creates a code calledfile and populated with the same value as we saw in the previous INI file example.
Read the file
Now let's see how to read files in Python.
import configparser def read_config(): config = () ('') # Read database configuration db_host = ('database', 'host') db_port = ('database', 'port') db_username = ('database', 'username') db_password = ('database', 'password') # Read API configuration api_key = ('api', 'key') api_url = ('api', 'url') return db_host, db_port, db_username, db_password, api_key, api_url db_host, db_port, db_username, db_password, api_key, api_url = read_config() print("Database Configuration:") print(f"Host: {db_host}") print(f"Port: {db_port}") print(f"Username: {db_username}") print(f"Password: {db_password}") print("\nAPI Configuration:") print(f"Key: {api_key}") print(f"URL: {api_url}")
This code will openfile and read the configuration in it. It then takes the corresponding key-value pairs from each section and stores them in the corresponding variable. Finally, the read configuration information is printed out.
This is the end of this article about how to set up and read files using Python. For more related Python settings and reading content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!