Olaf Erlandsen Olaf Erlandsen - 11 months ago 100
Ini Question

how to read and write INI file with Python?

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


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!!' )


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

Answer Source

This can be something to start with:

import configparser

config = configparser.ConfigParser()
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

You can find more at the official configparser documentation.