-2

I have config file as below:

[SECTION]
email = user1@exmple.com, user2@example.com

Now i want to append some more email ids in email using python, which should like as given below:

email = user1@exmple.com, user2@example.com, user3@example.com, user4@example.com

Please let me know how to do that.

Sraw
  • 18,892
  • 11
  • 54
  • 87
nancy
  • 51
  • 3
  • 11

4 Answers4

1
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('sample.ini')

a = parser.get('SECTION', 'email')
parser.set('SECTION', 'email', a + ', user3@example.com, user4@example.com')
with open('sample.ini', 'wb') as f:
    parser.write(f)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

One thing you can try is:

  1. Read the file in r+ mode
  2. Find the string email = .*\.com
  3. Concatenate your additional email addresses to that string
  4. write the data back to the file.
eiram_mahera
  • 950
  • 9
  • 25
0

This code handles if entry does not yet exist.

configFilePath = os.path.join(unreal.Paths.project_config_dir(), 'DefaultGame.ini')
gameConfig = SafeConfigParser()
gameConfig.read(configFilePath)
try:
    existing = gameConfig.get('/Script/Engine.AssetManagerSettings', 'MetaDataTagsForAssetRegistry')
    if PROTECTED_ASSET_METADATA_TAG_STRING not in existing:
        newEntry = existing[:-1] + ',"{}")'.format(PROTECTED_ASSET_METADATA_TAG_STRING)
    else:
        newEntry = ''
except NoOptionError:
    newEntry = '("{}")'.format(PROTECTED_ASSET_METADATA_TAG_STRING)
if newEntry:
    gameConfig.set('/Script/Engine.AssetManagerSettings', 'MetaDataTagsForAssetRegistry', newEntry)
    with open(configFilePath, 'wb') as f:
        gameConfig.write(f)
Paul E
  • 41
  • 3
0

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)
trohit
  • 319
  • 3
  • 6