首页 > 解决方案 > 我想使用 python 将 CSV 转换为 JSON 文件

问题描述

import csv
import json


# defining the function to convert CSV file to JSON file
def convjson(cleanedhm, js):
    # creating a dictionary
    mydata = {}

    # reading the data from CSV file
    with open(cleanedhm, encoding='utf-8') as csvfile:
        csvRead = csv.DictReader(csvfile)

        # Converting rows into dictionary and adding it to data
        for rows in csvRead:
            mykey = rows['hmid']
            mydata[mykey] = rows

            # dumping the data
    with open('cleanedhm', encoding='utf-8') as jsonfile:
        jsonfile.write(json.dumps(mydata, indent=4))

    # filenames


cleanedhm = r'mydatalist.csv'
js = r'mydatalist.json'

# Calling the convjson function
convjson(cleanedhm, js)

标签: javascriptpython

解决方案


Pandas 是一个非常棒的工具,在这种情况下,它只需两行非常简单的代码就可以满足您的需求!

import pandas as pd

csv = pd.read_csv (r'Path where the CSV file is saved\File Name.csv')
csv.to_json (r'Path where the new JSON file will be stored\New File Name.json')

推荐阅读