Skip to content

Instantly share code, notes, and snippets.

@quest4i
Created December 21, 2015 07:22
Show Gist options
  • Save quest4i/ec5fbf8d17de44ce0480 to your computer and use it in GitHub Desktop.
Save quest4i/ec5fbf8d17de44ce0480 to your computer and use it in GitHub Desktop.
ini (configparser) file to json format file
import os
import sys
from collections import OrderedDict
from configparser import ConfigParser
from configparser import ParsingError
import json
import click
@click.command()
@click.option('--inifile', default='config.ini', help='ini file to transfer json')
@click.option('--outfile', default='config.json', help='json file name')
def save_json(inifile, outfile):
"""ini config file to json format file"""
if not os.path.exists(inifile):
sys.stderr.write('no exist ini file')
raise SystemExit(1)
config = ConfigParser()
config.read(inifile, encoding='utf-8')
dict_cfg = OrderedDict()
for i in config.sections():
dict_cfg[i] = OrderedDict(config.items(i))
json_str = json.dumps(dict_cfg, indent=4, ensure_ascii=False)
print(json_str)
print("save a json file...")
with open(outfile, 'wt') as fout:
fout.write(json_str)
return 0
if __name__ == '__main__':
save_json()
@quest4i
Copy link
Author

quest4i commented Dec 21, 2015

커맨드 입력은 click 라이브러리를 이용해서 간단하게 만들고,
한글 등의 다국어 지원을 위해서는 ensure_ascii 설정을 하고,
원본 파일의 설정 순서를 유지하기 위해서 OrderedDict를 사용함.

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