如何使用 Python 将值附加到配置文件中的选项

How to append a value to an option in config file using Python

我的配置文件如下:

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

现在我想使用 python 在电子邮件中附加一些电子邮件 ID,如下所示:

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

请告诉我该怎么做。

您可以尝试的一件事是:

  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.
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)

此代码处理条目尚不存在的情况。

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)