【发布时间】:2020-04-12 16:33:38
【问题描述】:
使用以下 Python3 代码,我可以访问第一列的值,但无法访问后续列。错误是:
IndexError: 列表索引超出范围
with open('smallSample.txt', 'r') as file:
listOfLines = file.readlines()
for line in listOfLines:
print(line.strip())
header = listOfLines[0] #with all the labels
print(header.strip().split(','))
for row in listOfLines[1:]:
values = row.strip().split(',')
print(values[0]) #Able to access 1st row elements
print(values[1]) #ERROR Unable to access the Second Column Values
'''IndexError: list index out of range'''
存储的smallSample.txt数据为:
Date,SP500,Dividend,Earnings,Consumer Price Index,Long Interest Rate,Real Price,Real Dividend,Real Earnings,PE10
1/1/2016,1918.6,43.55,86.5,236.92,2.09,2023.23,45.93,91.22,24.21
2/1/2016,1904.42,43.72,86.47,237.11,1.78,2006.62,46.06,91.11,24
3/1/2016,2021.95,43.88,86.44,238.13,1.89,2121.32,46.04,90.69,25.37```
【问题讨论】:
-
如果您需要我方面的任何意见,请发表评论。
-
请修正你的错误和伴随它的散文。
-
您是否尝试过调试并查看要拆分的内容?
-
第 11 行输出:
print(values) -
[''] ['1/1/2016', '1918.6', '43.55', '86.5', '236.92', '2.09', '2023.23', '45.93', '91.22', '24.21'] [''] ['2/1/2016', '1904.42', '43.72', '86.47', '237.11', '1.78', '2006.62', '46.06', '91.11', '24'] [''] ['3/1/2016', '2021.95', '43.88', '86.44', '238.13', '1.89', '2121.32', '46.04', '90.69', '25.37']
标签: python python-3.x csv data-science