简体   繁体   English

遍历CSV文件时“列表索引超出范围”

[英]“list index out of range” when iterating through a csv file

A strange thing is happening over here, I'm trying to add two extra line to an existing csv file, so I open it (edit1.csv), re-write it to a new file (edit2) with two extra line (one with the number 100 written on the first space, and a second row with the number 9 in the first three space. 这里发生了一件奇怪的事情,我正在尝试向现有的csv文件中添加两行,因此我将其打开(edit1.csv),并使用两行额外的内容将其重写为新文件(edit2)(一在第一个空格上写上数字100,第二行在前三个空格上写上数字9。

ifile  = open('C:\PyProject\edit1.csv', "rb")
reader = csv.reader(ifile)
edited  = open('C:\PyProject\edit2.csv', "wb")
writer = csv.writer(edited, delimiter=',')
for row in reader:
    writer.writerow(row)
writer.writerow([100])
writer.writerow('999')
edited.close()
ifile.close()

So far so good, I get a new file (edit2.csv) that looks exactly like I want it to look. 到目前为止一切顺利,我得到了一个新文件(edit2.csv),它看起来和我想要的样子完全一样。

The problem is when I'm trying to iterate through the new file in order to find the rows in which the second column is empty (see below), I get an error 问题是当我尝试遍历新文件以查找第二列为空的行(请参见下文)时,出现错误

- --

with open('C:\PyProject\edit2.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    sec_col = []
    for row in readCSV:
        blanker = row[1]
        sec_col.append(blanker)
    trial_index = [i for i,x in enumerate(sec_col) if x == '']   

- --

  blanker = row[1]
    IndexError: list index out of range

The strange thing is that if i open the new file and delete all the blank rows after the two I have manually added, the code runs just fine. 奇怪的是,如果我打开新文件并在手动添加两行后删除所有空白行,则代码可以正常运行。

Sorry if my code is a bit messy, I'm still new at this :) 抱歉,如果我的代码有点混乱,我仍然是新手:)

Thanks. 谢谢。

The only wrong part is accessing row[1] directly. 唯一错误的部分是直接访问row[1]

If row has only 1 row, then it throws exception when you are trying to reach the second. 如果row只有1行,那么当您尝试到达第二行时会引发异常。

Just modify the code like this: 只需像这样修改代码:

for row in readCSV:
    if len(row) < 2: # row[1] not exists
        sec_col.append(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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