I need to read, write and create an INI file with Python3.
FILE.INI
default_path = "/path/name/"
default_file = "file.txt"
Python File:
# Read file and and create if it not exists
config = iniFile( 'FILE.INI' )
# Get "default_path"
config.default_path
# Print (string)/path/name
print config.default_path
# Create or Update
config.append( 'default_path', 'var/shared/' )
config.append( 'default_message', 'Hey! help me!!' )
UPDATED FILE.INI
default_path = "var/shared/"
default_file = "file.txt"
default_message = "Hey! help me!!"
To read and write INI files, we can use the configparser module. This module is a part of Python's standard library and is built for managing INI files found in Microsoft Windows. This module has a class ConfigParser containing all the utilities to play around with INI files.
Steps to use the Ini class INIFile ini = new INIFile("C:\\test. ini"); Use IniWriteValue to write a new value to a specific key in a section or use IniReadValue to read a value FROM a key in a specific Section.
Python can have config files with all settings needed by the application dynamically or periodically. Python config files have the extension as . ini. We'll use VS Code (Visual Studio Code) to create a main method that uses config file to read the configurations and then print on the console.
This can be something to start with:
import configparser
config = configparser.ConfigParser()
config.read('FILE.INI')
print(config['DEFAULT']['path']) # -> "/path/name/"
config['DEFAULT']['path'] = '/var/shared/' # update
config['DEFAULT']['default_message'] = 'Hey! help me!!' # create
with open('FILE.INI', 'w') as configfile: # save
config.write(configfile)
You can find more at the official configparser documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With