Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and write INI file with Python3?

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!!"
like image 404
Jorge Olaf Avatar asked Oct 15 '22 11:10

Jorge Olaf


People also ask

How read and write INI file in Python?

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.

How do I read and write 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.

What is config INI file in Python?

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.


1 Answers

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.

like image 147
Rik Poggi Avatar answered Oct 19 '22 03:10

Rik Poggi