Just updating @Rakesh 's answer as I saw a deprecation warning like :
DeprecationWarning: The SafeConfigParser class has been renamed to
ConfigParser in Python 3.2. This alias will be removed in Python 3.12.
Use ConfigParser directly instead. parser = SafeConfigParser()
Some python modules have changed since then.
in Python 3, ConfigParser
has been renamed configparser
. See Python 3 ImportError: No module named 'ConfigParser for more details.
#!/usr/bin/env python3
import os
from configparser import ConfigParser
abs_file_name = 'sample.ini'
parser = ConfigParser()
rec = ''
# if file already exists, read it up
if os.path.isfile(abs_file_name):
parser.read(abs_file_name)
rec = parser.get('SECTION', 'email')
else: # write a brand new config file
parser.add_section('SECTION')
# then add the new contents
parser.set('SECTION', 'email', rec+', user3@example.com, user4@example.com')
# save contents
with open(abs_file_name, 'w') as f:
parser.write(f)