0

我正在研究将 csv 文件转换为 ArcGIS shapefile 的项目,这涉及将输出写入单独的文件。我为每一行中的每一列创建了一个列表,并试图索引第 36 和 37 列。但是,list index out of range这样做时我收到一条错误消息。关于我可能在做什么的任何建议?

while line:
    count = count + 1
    line = inFile.readline()
    print 'Row', count, 'line info=', line[:72]
    lineList = line.split(',')
    newList = lineList[:72]
    print 'line info =', newList   
    for item in newList[36]:
        item.replace("", "0")
    for item in newList[37]:
        item.replace("", "0")
    newLine = ','.join(newList)
    newLine = newLine + '\n'   
    formatLine = newLine.replace("/","_")
    outFile.write(formatLine) 
4

1 回答 1

3

如果您可以编辑问题以包含错误所说的索引超出范围问题的哪一行,这将有所帮助。

我相信问题很可能是这样的:

while line: # line is something other than whitespace
    line = inFile.readline() # next line becomes whitespace, there might be a trailing newline character in the file
    ...
    newList = line.split(',')[:72] # Even if line.split(',') doesn't return a list with at least 72 values, there will not be an error here- it will merely return a shorter list.
    for item in newList[36]: # newList is probably an empty list at this point.
    ...

在旁注中,我在 Python shell 中输入了以下内容:

>>> bool("")
False
>>> bool(" ")
True
>>> bool("\n")
True

正如你所看到的,如果有一行只有一个空格,那么循环也会继续。

于 2013-04-20T00:33:06.043 回答