我正在使用python和simplekml创建器创建kml文件。 由于某种原因,它会创建两个kml文件,而不会创建第三个。数据似乎很好。这是代码:
times=open("E:\\Python\Copyofresttable.csv","r")
import time
import csv
import simplekml
from time import strftime, localtime
dayoftheweekvariable = strftime("%A", localtime())
print dayoftheweekvariable
kml = simplekml.Kml()
if dayoftheweekvariable == "Monday":
for line in times:
a = line.split(',')
if a[2] == "Monday":
print a[5]
if dayoftheweekvariable == "Tuesday":
for line in times:
a = line.split(',')
if a[2] == "Tuesday":
print a[5]
if dayoftheweekvariable == "Wednesday":
for line in times:
a = line.split(',')
if a[1]== "Iron Hill" and a[2] =="Wednesday":
kml.newpoint(name="Iron Hill", coords=[(-75.605507,39.960504)], description=a[5])
kml.save("pythonmap.kml")
print "Creating KML"
if a[1]== "Side Bar and Resturant" and a[2] =="Wednesday":
kml.newpoint(name="Side Bar and Resturant", coords=[(-75.604805,39.960591)], description=a[5])
kml.save("pythonmap.kml")
print "Creating KML"
if a[1]== "Barnaby's" and a[2] =="Wednesday":
kml.newpoint(name="Barnaby's", coords=[(-75.604049,39.959488)], description=a[5])
kml.save("pythonmap.kml")
print "Creating KML"
显然在星期三晚上测试了这个...至于最后三个if语句,无论我把它们放入什么顺序,它都会为Iron Hill和Barnaby创造一个kml而不是侧栏。这是它返回的结果:
Wednesday
Creating KML
Creating KML
Traceback (most recent call last):
File "C:/Users/75IV740906/Desktop/py117", line 26, in <module>
if a[1]== "Iron Hill" and a[2] =="Wednesday":
IndexError: list index out of range
错误消息会调出if if语句在顶部的内容。我很难过。希望我的问题有意义(为什么它给我这个错误信息,只要创建两个kml,无论if语句的顺序是什么)
答案 0 :(得分:0)
更改
times=open("E:\\Python\Copyofresttable.csv","r")
为:
times=open("E:\\Python\Copyofresttable.csv","r").read()
在第一行添加
print('#Times: {0}'.format(len(times.split())))
确保你有足够的线......
<强>更新强>:
你的回溯(在评论中)显示你的(第一个?!)dayoftheweek
似乎是一个星期三,这就是你的前两个ifs被忽略的原因。然后看起来您的列表a
没有足够的条目。
您可以使用print("# a: {0}".format(len(a)))
因此,如果您有少于3个条目a[2]==
必须失败,因为list index out of range
; - )
啊,我一开始没有正确地阅读你的问题。如果每个第一个if语句都抛出异常,那就更有意义了......
更新2:
顺便说一下:你应该将你的for line in times:
循环重新排列成一种不太冗余的方式,例如:
lines=open("E:\\Python\Copyofresttable.csv","r").readlines()
...
for line in lines:
a = line.split(',')
if a[2] == "Monday" == dayoftheweek:
...
elif a[2] == "Tuesday" == dayoftheweek:
...
elif a[1]== "Iron Hill" and a[2] =="Wednesday" == dayoftheweek:
...
更新3:
如果省略某些行,你可以通过做类似的事情来“欺骗”一点:
a = line.split(',')
if len(a) < 6:
continue # ignores the rest of the loop and jumps stright to the next iteration