python实现json、ini、csv格式的文件转换

python实现json、ini、csv格式的文件转换

import json
from configparser import ConfigParser
 
 
# test.json
'''
[{"name": "apple", "price": "10", "amount": "3"},
{"name": "tesla", "price": "100000", "amount": "1"},
{"name": "mac", "price": "3000", "amount": "2"},
{"name": "lenovo", "price": "30000", "amount": "3"},
{"name": "chicken", "price": "10", "amount": "3"}]
'''
 
# mysql.ini
'''
[DEFAULT]
a = test
[mysql]
default-character-set = utf8
[mysqld]
test1 = 200
datadir = /dbserver/data
port = 33060
character-set-server = utf8
sql_mode = NO_ENGINE_SUBSTRITUTION,STRICT_TRANS_TABLES
c = True
[test]
test1 = 100
'''
 
# sun.csv
'''
name,price,amount
apple,10,3
tesla,100000,1
mac,3000,2
lenovo,30000,3
chicken,10,3
'''
 
 
# file:json to csv
def json2csv(json_path, csv_path):
    with open(json_path, 'r', encoding='utf-8') as f1:
        with open(csv_path, 'w', newline='') as f2:
            ls = json.load(f1)
            data = [list(ls[0].keys())]
            for item in ls:
                data.append(list(item.values()))
            for line in data:
                f2.write(','.join(line) + '\n')
 
 
# file:csv to json
def csv2json(json_path, csv_path):
    ls = []
    with open(csv_path, 'r', newline='') as f1:
        with open(json_path, 'w', encoding='utf-8') as f2:
            for line in f1:
                ls.append(line.replace('\n', '').split(','))
            # print(ls)
            for i in range(1, len(ls)):
                ls[i] = dict(zip(ls[0], ls[i]))
            json.dump(ls[1:], f2, indent=4)
            # 将Python数据类型转换成json格式,编码过程
            # 默认是顺序存放,sort_keys是对字典元素按照key进行排序
            # indent参数用语增加数据缩进,使文件更具有可读性
 
 
def ini2json(json_path, ini_path):
    d = {}
    cfg = ConfigParser()
    cfg.read(ini_path)
    for s in cfg.sections():
        # print(s)
        # print(cfg.items(s))  # 指定section,返回二元组
        d[s] = dict(cfg.items(s))
    with open(json_path, 'w') as f:
        json.dump(d, f)
 
 
def json2ini(json_path, ini_path):
    with open(json_path, 'r') as f1:
        with open(ini_path, 'w') as f2:
            dic = json.load(f1)
            cfg = ConfigParser()
            # print(ls)
            for section, section_items in zip(dic.keys(), dic.values()):
                cfg._write_section(f2, section, section_items.items(), delimiter='=')
 
 
if __name__ == '__main__':
    ini2json('./test2.json', './mysql.ini')
    json2ini('./test2.json', './sun.ini')
    json2csv('./test.json', './sun.csv')
    csv2json('./b.json', './sun.csv')

参考 https://blog.csdn.net/sqsltr/article/details/92630384?utm_term=pythonini

您可能还喜欢...

发表回复