【问题标题】:converting csv to Json without pandas (python) [closed]将csv转换为没有熊猫的Json(python)[关闭]
【发布时间】:2019-12-20 15:39:40
【问题描述】:

我是一名学生,我有一个任务,我必须在不使用 Pandas 的情况下将 csv 文件转换为 Json 格式。有没有办法在python中实现这一点?

谢谢,

【问题讨论】:

标签: python json csv


【解决方案1】:

你可以试试这个:

import csv
import json

with open('test.csv', 'r') as csvfile, open('file.json', 'w') as jsonfile:
    fieldnames = ("col_1", "col_2")  # as you have in your csv
    reader = csv.DictReader( csvfile, fieldnames)
    json.dump(list(reader), jsonfile)

读取 JSON 文件:

with open('file.json') as json_file:
    data = json.load(json_file)
    print data

【讨论】:

  • 这不起作用。它使 JSONLines,不是一个有效的 JSON 文件
  • 对不起,roganjosh,当我尝试时,它确实创建了一个 JSON 文件。我相信@sue 也已经尝试并验证了它。
  • 那么如果你用json.load()一次性打开文件会发生什么?由于换行,它会出错
  • json.load 无法解码多个 json 对象,如果需要通过加载读取,则需要将所有行包装在一个列表中并 dumped in。因为它不是需求,我没这么写。
猜你喜欢
  • 1970-01-01
  • 2021-03-22
  • 2017-06-04
  • 2010-10-14
  • 1970-01-01
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多