我試圖通過讀取 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(最近一次呼叫最后一次) 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
型別錯誤:字串索引必須是整數
uj5u.com熱心網友回復:
您沒有以正確的方式閱讀 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物件,迭代它會將每一行作為字典回傳。
uj5u.com熱心網友回復:
您可以使用csv.DictReader.
reader = csv.DictReader(csvfile)
for line in reader:
key = line['Order ID']
contents[key] = m
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/313606.html
