I"m unable to read .csv rows recursively. Why is this showing me an error: IndexError: list index out of range?

I"m unable to read .csv rows recursively. Why is this showing me an error: IndexError: list index out of range?

def kmlForLab2(x,y):
    #XYpoints1_wgs84
    #XYpoints1_wgs84.csv
    print(x,y)
    
    #Input the file name."JoeDupes3_forearth"
    fname = input("Enter file name WITHOUT extension: ")
    data = csv.reader(open(fname + '.csv'), delimiter = ',')
    
    #Skip the 1st header row.
    #data.next()
    #Open the file to be written.
    f = open('Buffered_kml.kml', 'w')
    
    #Writing the kml file.
    f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
    f.write("<kml xmlns='http://earth.google.com/kml/2.0'>\n")
    f.write("<Document>\n")
    f.write("<!-- first buffer -->")
    f.write("<Placemark>\n")
    f.write("   <name>" + fname + '.kml' +"</name>\n")
    f.write("   <Polygon> <outerBoundaryIs> <LinearRing>\n")
    f.write("           <coordinates>\n" )
    next(data)
    for row in data:
        #every_row = (', '.join(row))
        f.write(str(( row[x])) + "," + (str( row[y]))+ "\n") 
    f.write("           </coordinates>\n" )
    f.write("   </LinearRing> </outerBoundaryIs> </Polygon> \n")
    f.write("</Placemark>\n")
    f.write("</Document>\n")
    f.write("</kml>\n")
    f.close()
    print ("File Created. ")
    print ("Press ENTER to exit. ")

#run the function
kmlForLab2(1,2)

上面的代码适用于这个具有 header:

的 .csv 文件
FID,X,Y
0,170.5464722,-45.75102725
1,170.5668576,-45.74410705
2,170.5830378,-45.75211941
3,170.5750982,-45.74847698
4,170.5836827,-45.75020334
5,170.5939802,-45.74689513
6,170.5857636,-45.74719562
7,170.5754473,-45.75424382
8,170.5646303,-45.7570933
9,170.5720296,-45.75808701
10,170.5690206,-45.74853323

但这个文件没有 header 并且有空行 中间:

0,-78.66408134601733,9771.5546110773,1

0,-78.65548895240566,9771.551542342384,2

0,-78.65033681160779,9771.586626160439,3

0,-78.65335636231875,9771.627622956843,4

0,-78.66177515305098,9771.63688377605,5

0,-78.66785531910878,9771.60584192237,6

0,-78.66600112895804,9771.563037346988,7

0,-78.65791969380092,9771.547876588438,8

0,-78.651044721165,9771.57425465822,9

第一个 .csv 文件是提供给我的,而第二个 .csv 是在 python 中生成的。我想我在生成 .csv 文件时出错了?

第一个问题是分隔符

data = csv.reader(open(fname + '.csv'), delimiter = ',')

您正在使用 ,(逗号),但您的文件似乎可能使用制表符作为分隔符。

那么,你应该使用

data = csv.reader(open(fname + '.csv'), delimiter='\t')

编辑

如果某些行可能包含的值不够,请在访问前检查

    for row in data:
        if len(row) > max(x,y):
            f.write(str(( row[x])) + "," + (str( row[y]))+ "\n")

您需要跳过没有足够字段的行。

cols_needed = max(x, y):
for row in data:
    if len(row) > cols_needed:
        f.write(f'{row[x]},{row[y]}\n')