Olaf Erlandsen Olaf Erlandsen - 3 months ago 29
Ini Question

how to read and write INI file with Python?

i need read, write and create INI file with Python3.

FILE.INI

default_path = "/path/name/"
default_file = "file.txt"


Python File:

# read file and if not exists
ini = iniFile( 'FILE.INI' )

# Get and Print Config Line "default_path"
getLine = ini.default_path

# Print (string)/path/name
print getLine

# Append new line and if exists edit this line
ini.append( 'default_path' , 'var/shared/' )

ini.append( 'default_message' , 'Hey! help me!!' )


UPDATE FILE.INI

default_path = "var/shared/"
default_file = "file.txt"
default_message = "Hey! help me!!"

Answer

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.