Created
December 21, 2015 07:22
-
-
Save quest4i/ec5fbf8d17de44ce0480 to your computer and use it in GitHub Desktop.
ini (configparser) file to json format file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
커맨드 입력은 click 라이브러리를 이용해서 간단하게 만들고,
한글 등의 다국어 지원을 위해서는 ensure_ascii 설정을 하고,
원본 파일의 설정 순서를 유지하기 위해서 OrderedDict를 사용함.