尝试将 csv 转换为字典列表时出现索引错误

问题描述 投票:0回答:1

我是编码新手,所以这可能是一个愚蠢的问题。我不明白列表索引如何超出范围。变量“I”范围应该是文件中的行数,并且“标题”只要“标题”中有标题即可。但我收到一条错误消息:“data[title].append(row[i]) IndexError:列表索引超出范围”

谢谢你。

csv 文件如下所示:

DATE,OPEN,HIGH,LOW,CLOSE,SPREAD
2024-03-25 00:00,1.08071,1.08073,1.08068,1.08072,95
2024-03-25 00:01,1.08074,1.08082,1.08074,1.08079,73
2024-03-25 00:02,1.0808,1.08094,1.08078,1.08089,172
2024-03-25 00:03,1.0809,1.08094,1.08085,1.08092,167
2024-03-25 00:04,1.08093,1.08093,1.0809,1.08092,62
2024-03-25 00:05,1.08091,1.08092,1.08088,1.08091,27
2024-03-25 00:06,1.08091,1.08094,1.08088,1.08088,70
2024-03-25 00:07,1.08087,1.08096,1.08087,1.08095,25
2024-03-25 00:08,1.08096,1.08096,1.08092,1.08092,65
2024-03-25 00:09,1.08092,1.08092,1.08087,1.08089,68
2024-03-25 00:10,1.08088,1.08088,1.08079,1.08079,28

这是我的代码:

import csv
import datetime

import matplotlib.pyplot as plt


filename = "pathtocsv.csv"

with open(filename, "r") as file:
    csv_reader = csv.reader(file)
    headers = next(csv_reader)
   
    data = {}
    for title in headers:
        data[title] = []

    for row in csv_reader:
        for i, title in enumerate(headers):
            data[title].append(row[i])
    
for i in range(len(data["DATE"])):
    data["DATE"][i] = datetime.datetime.strptime(data["DATE"][i],'%Y-%m-%d %H:%M')
        
for i in range(len(["OPEN"])):
    data["OPEN"][i] = float(["OPEN"][i])

for i in range(len(["CLOSE"])):
    data["CLOSE"][i] = float(["CLOSE"][i])
   

fig, ax = plt.subplots()
ax.plot(["DATE"], ["OPEN"])
ax.plot(["DATE"], ["CLOSE"])
fig.autofmt_xdate()
fig.show()
python csv indexing
1个回答
0
投票

没有足够的积分来添加评论,因此添加为答案。 您能检查一下这是否适用于您的文件吗? 来自文档

If csvfile is a file object, it should be opened with newline=''

在代码中将是-

with open(filename, newline='') as file:
© www.soinside.com 2019 - 2024. All rights reserved.