Python json文件与csv文件的相互转换

'''JSON转CSV'''
json格式示例
[{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }]'''


import csv
import json


def trans(jsonpath, csvpath):
    json_file = open(jsonpath, 'r', encoding='utf8')
    csv_file = open(csvpath, 'w', newline='')
    keys = []
    writer = csv.writer(csv_file)

    json_data = json_file.read()
    dic_data = json.loads(json_data, encoding='utf8')

    for dic in dic_data:
        keys = dic.keys()
        # 写入列名
        writer.writerow(keys)
        break

    for dic in dic_data:
        for key in keys:
            if key not in dic:
                dic[key] = ''
        writer.writerow(dic.values())
    json_file.close()
    csv_file.close()


if __name__ == '__main__':
    trans('my.json', 'my.csv')
“”“ CSV转JSON ”“”
# 法一
import csv
import json

file_path = r"C:\Users\zhi\Desktop\myfloder\sql_use_csv\0101.csv"
csvfile = open(file_path, 'r')
jsonfile = open('file.json', 'w')
# csv的列名
fieldnames = ('品种', '合约号', '多空', '总仓', '可用', '今仓', '今可用', '开仓均价', '盈利价差', '逐笔浮盈',
              '浮盈比例', '价值', '保证金', '资金占比', '持仓均价', '盯市浮盈', '投保', '交易账号')
reader = csv.DictReader(csvfile, fieldnames)
data_list = [row for row in reader]
out = json.dumps(data_list[1:], ensure_ascii=False)
jsonfile.write(out)


# 法二
import json
import pandas

csv_file = r"C:\Users\zhi\Desktop\myfloder\sql_use_csv\0101.csv"
df = pandas.read_csv(csv_file, encoding="gbk")
print(df.head())
# key_list = df.columns
dict_list = []
for index, row in df.iterrows():
    print(index)
    dict_row = row.to_dict()
    print(dict_row)
    dict_list.append(dict_row)
    print("--------------------------------------------------")

with open("file.json", mode="a") as f:
    f.write(json.dumps(dict_list, ensure_ascii=False))

你可能感兴趣的:(Python)