A config file is a file that your program refers to in order to get configuration parameters and settings. So, it’s more like a global variable, just one that holds a value across all the files in a project, instead of just methods/functions in a single program/script. For example, you can simply set the value of a port as 1167 in your config file, and simply have your programs refer to the port in the config file. This way you won’t have to change your port’s value across files if you later change it.
Config files are plaintext files, often written in formats: ini, json, yaml and xml. Most resources I found online were for ini format, but once you’re acquainted with the parts of a config file, format pretty much remains the same with just the syntactical changes.
Creating a config file:
- So firstly, you import the module that will provide the basic configuration for your program. If writing a .ini file, import the ConfigParser file; for JSON, you import json.
- Use the method corresponding to your file format that converts your python object (
Dictionary
in this case) into a serialized string (JSON formatted string here). For .ini files its ConfigParser() method, and it is json.dumps() method for JSON files. - Lastly, you use a method that writes your string into a plaintext file. In JSON, the
write()
method writes that formatted JSON string to the filejson_data.json
.
(I used a json file and python for the purpose of this example)// import the module corresponding to what format you want your
// config file in.import json // Save your json string into an objectjson_data = { “port” : “1167”, “language” : “python”, “type” : “config file” } // Use the json.dumps method to convert your python object into a
// json string json_string = json.dumps(json_data) // Open the file where you want your configuration settings or
// parameters to be written. By using ‘w’, you instruct the
// program to create a new file in case it is not already present.with open(“config_data.json”, “w”) as jsonfile: jsonfile.write(json_string) print(“JSON config file created”) //Optional output statement//Check for the creation of a config_data.json file (or whatever you named your file) to ensure that the file ran successfully.
Reading a config file in your program:
Reading data from a config file pretty much like reading any other plaintext file (json in this case). Here’s a sample code:import json json_file = open(‘config_data.json’, “r”)data = json.load(json_file) //Note: The json.load() accepts a file object, while the
// json.loads() accepts a json string. These methods parse the json
// data and load a Python dictionary with it.print(data) // This will print the entire contents of the json fileprint(data[‘language’]) // This would print the value corresponding to the language key.
References:
Leave a Reply
You must be logged in to post a comment.