python - 在python中将csv文件转换为json格式
问题描述
我已经编写了一个代码来转换我的 csvfile 是 '|' 分隔文件以获取特定的 json 格式。
CSV 文件格式:
comment|address|city|country
crowded|others|others|US
pretty good|others|others|US ....
我也尝试过其他代码,因为我是 python 新手,我被困在两者之间。如果有人帮助我纠正我正在做的错误,那将会很有帮助。
import csv
import json
from collections import OrderedDict
csv_file = 'test.csv'
json_file = csv_file + '.json'
def main(input_file):
csv_rows = []
with open(input_file, 'r') as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
entry = OrderedDict()
for field in title:
entry[field] = row[field]
csv_rows.append(entry)
with open(json_file, 'w') as f:
json.dump(csv_rows, f, sort_keys=True, indent=4, ensure_ascii=False)
f.write('\n')
if __name__ == "__main__":
main(csv_file)
我想要json格式如下
{
"reviewer": {
"city": "",
"country": ""
"address": "Orlando, Florida"
},
但我得到这样的输出:
[
{
"COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"Crowded"|"Others"|"Others"|
},
{
"COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"pretty good"|"Others"|"Others"|
},
解决方案
您缺少分隔符参数。代替:
reader = csv.DictReader(csvfile)
利用:
reader = csv.DictReader(csvfile, delimiter='|')
推荐阅读
- powershell - 使用一个字段降序然后在第二个字段上升序对数据进行排序?
- sql-server - 如何使两列枢轴和其他正常
- c# - 更新到 .net core 2.1 后出现大量波浪线 - “可能需要提供运行时策略”
- ruby-on-rails - Rails中嵌套关联中未定义的方法“customer_name”
- laravel - “unique:table,column,except,idColumn”中的“except”和“idColumn”指的是什么?来自 Laravel 文档
- css - 是否可以在 Firefox 开发人员工具中查看所有已编辑的样式?
- javascript - 如何使用 vuejs 和 bootstrap-vue 下载 pdf 文件
- java - 如果我使用“localhost”,是否保证客户端是本地的?(考虑到我可以编辑系统主机文件)
- reactjs - Laravel View/Blade 和 React 的问题
- python-3.x - 如何删除数据框中具有超过 x 个 Null 值的行?