javascript - 我想使用 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)
解决方案
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')
推荐阅读
- python - 无法在 Python 中导入“漂亮的”
- python - 有没有办法使用 Python 在视频的开头添加图像?
- sql-server - 使用 INSERT-SELECT 插入新记录时出现问题
- java - 将多个用户输入存储到多个单独的数组中
- c - 用无用的 printf 调用修复了条件返回值错误
- sql - 如果值已经存在,有没有办法从其他两列添加一个 int 的连接值来提供一个列?
- php - Docker 中的 PHP - fopen() 或 file_put_contents() 无法写入 /proc/1/fd/2 以进行标准输出写入
- android - 如何在 Android 中优化后台任务
- c# - 为什么我不能像使用列表一样过滤 IQueryable?
- r - filelist() 不能在 for 循环中执行