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

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值