当访问从CSV文件读取行时,列表索引超出范围 [英] List Index Out of Range when accessing row read from CSV file

查看:1007
本文介绍了当访问从CSV文件读取行时,列表索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在python中读取一个csv文件。 csv文件有1400行。我使用以下命令打开csv文件:

  import csv 
import sys
f = csv.reader (open(/ Users / Brian / Desktop / timesheets_9_1to10_5small.csv,rU),
dialect = csv.excel_tab)

然后我尝试循环遍历该文件,使用以下命令从每行中取出第一个名称:

  for f:
g = row
s = g [0]
end_of_first_name = s.find(,)
first_name = s [0:end_of_first_name ]

我收到以下错误信息:



< blockquote>

跟踪(最近一次调用):

模块中的第3行的文件

s = g [0]

IndexError:list index超出范围


有人知道我为什么会收到此错误消息以及如何纠正它? / p>

解决方案

您应该不要以通用换行模式打开文件( / code>)。以二进制模式打开文件:

  f = csv.reader(open(/ Users / Brian / Desktop / timesheets_9_1to10_5small。 csv,rb),
dialect = csv.excel_tab)



接下来,使用 print repr(row)打印您的行以验证您是否正在获取您期望的输出。使用 repr 代替常规字符串表示,可以更好地显示正在处理的对象的类型,突出显示字符串与整数之间的差异('1' 1 )。



如果您想要选择字符串的一部分(直到分隔符,例如逗号),请使用 .split(delimiter,1) .partition(delimiter)[0]

 >>> 'John,Jack,Jill'.partition(',')[0] 
'John'


I am trying to read a csv file in python. The csv file has 1400 rows. I opened the csv file using the following command:

import csv  
import sys             
f=csv.reader(open("/Users/Brian/Desktop/timesheets_9_1to10_5small.csv","rU"),
    dialect=csv.excel_tab)

Then I tried to loop through the file to pull the first name from each row using the following commmands:

for row in f:
    g=row
    s=g[0]  
    end_of_first_name=s.find(",")
    first_name=s[0:end_of_first_name]

I got the following error message:

Traceback (most recent call last):
File "", line 3, in module
s=g[0]
IndexError: list index out of range

Does anyone know why I would get this error message and how I can correct it?

解决方案

You should not open the file in universal newline mode (U). Open the file in binary mode instead:

f=csv.reader(open("/Users/Brian/Desktop/timesheets_9_1to10_5small.csv","rb"),
    dialect=csv.excel_tab)

CSV does it's own newline handling, including managing newlines in quotes.

Next, print your rows with print repr(row) to verify that you are getting the output you are expecting. Using repr instead of the regular string representation shows you much more about the type of objects you are handling, highlighting such differences as strings versus integers ('1' vs. 1).

Thirdly, if you want to select part of a string up to a delimiter such as a comma, use .split(delimiter, 1) or .partition(delimiter)[0]:

>>> 'John,Jack,Jill'.partition(',')[0]
'John'

这篇关于当访问从CSV文件读取行时,列表索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆