Skip to content

Instantly share code, notes, and snippets.

@andreipak
Created October 23, 2014 06:46
Show Gist options
  • Save andreipak/4e0885e9492101c7140d to your computer and use it in GitHub Desktop.
Save andreipak/4e0885e9492101c7140d to your computer and use it in GitHub Desktop.
copy config keys within section using ConfigParser
import ConfigParser, os
config_src = ConfigParser.ConfigParser()
config_dst = ConfigParser.ConfigParser()
config_keys = "host user passwd name".split()
config_keys.reverse()
dst_cfg_path = 'cfg1.ini'
src_cfg_path = 'cfg2.ini'
section = 'db'
config_dst.read([os.path.expanduser(dst_cfg_path)])
config_src.read([os.path.expanduser(src_cfg_path)])
for key in config_keys:
config_dst.set(section, key,
config_src.get(section, key))
out = 'cfg3.ini'
with open(out, 'wb') as configfile:
config_dst.write(configfile)
@andreipak
Copy link
Author

@foobar167
Copy link

foobar167 commented Dec 11, 2017

# Copy whole section. Doesn't depend on key names and their order.
for key, value in config_src.items(section):
    config_dst.set(section, key, value)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment