【问题标题】:Python: convert csv file to json filePython:将csv文件转换为json文件
【发布时间】:2021-10-12 19:50:08
【问题描述】:

我正在尝试通过读取 csv 文件的内容并将其写入新的 json 文件来将 csv 文件转换为 json 文件。我在尝试将 csv 文件的一列转换为字典键时遇到错误。我该如何解决这个错误?

我的代码供参考:

import csv 
import json

def jsonformat(infile,outfile):
    contents = {}
    csvfile = open(infile, 'r')
    reader = csvfile.read()

    for m in reader:
        key = m['Order ID']
        contents[key] = m
    
    jsonfile = open(outfile, 'w')
    json_contents = json.dumps(contents, indent = 4)
    jsonfile.write(json_contents)

    csvfile.close()
    jsonfile.close()
    return json_contents



infile = 'orders.csv'
outfile = 'orders.json'

output = jsonformat(infile,outfile)

print(output)

错误信息: TypeError Traceback(最近一次调用最后一次) 在 28 输出文件 = 'orders.json' 29 ---> 30 输出 = jsonformat(infile,outfile) 31 32 打印(输出)

in jsonformat(infile, outfile) 12 阅读器中的 m 为 13: ---> 14 key = m['订单ID'] 15 内容[键] = m 16

TypeError:字符串索引必须是整数

【问题讨论】:

    标签: python json csv


    【解决方案1】:

    您没有以正确的方式读取 CSV 文件。使用csv.DictReader 将每一行作为字典读取。然后,您就可以使用for m in reader: key = m['Order ID']

    reader = csvfile.read() 更改为reader = csv.DictReader(csvfile)

    到目前为止,reader 是一个包含文件所有内容的字符串。 for m in reader 使m 成为此字符串中的每个字符,并且您无法访问字符上的"Order ID" 键。

    进行更改后,reader 将成为 DictReader 对象,对其进行迭代会将每一行作为字典返回。

    【讨论】:

    • 感谢您的帮助!
    【解决方案2】:

    您可以使用csv.DictReader

    reader = csv.DictReader(csvfile)
    for line in reader:
        key = line['Order ID']
        contents[key] = m
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2023-03-03
    • 2019-03-25
    • 2021-01-31
    • 1970-01-01
    • 2015-01-13
    • 2018-07-14
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多