简体   繁体   中英

Python: convert csv file to json file

I am trying to convert a csv file to a json file by reading the content of the csv file and writing it to a new json file. I am encountering an error that is at the point where I try to make a column of the csv file into dictionary keys. How can I resolve this error?

My code for reference:

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)

在此处输入图片说明

error message: TypeError Traceback (most recent call last) in 28 outfile = 'orders.json' 29 ---> 30 output = jsonformat(infile,outfile) 31 32 print(output)

in jsonformat(infile, outfile) 12 13 for m in reader: ---> 14 key = m['Order ID'] 15 contents[key] = m 16

TypeError: string indices must be integers

You aren't reading the CSV file the correct way. Use csv.DictReader to read each row as a dictionary. Then, you'll be able to use for m in reader: key = m['Order ID'] .

Change reader = csvfile.read() to reader = csv.DictReader(csvfile)

As of now, reader is a string that contains all the contents of your file. for m in reader makes m each character in this string, and you cannot access the "Order ID" key on a character.

After you make the change, reader will be a DictReader object, and iterating over it will return each row as a dictionary.

You can use csv.DictReader .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM