2

我正在使用 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's 创建一个 kml,但不会为侧栏创建一个 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 语句的顺序如何,都只创建两个 kmls)

4

1 回答 1

0

改变

times=open("E:\\Python\Copyofresttable.csv","r")

至:

times=open("E:\\Python\Copyofresttable.csv","r").read()

在你的第一行并添加一个

print('#Times: {0}'.format(len(times.split())))

以确保您有足够的线路...

更新

您回溯(在评论中)表明您的(第一个?!)dayoftheweek似乎是星期三,这就是为什么您的第一个两个 if 被忽略的原因。然后,您的列表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
于 2012-11-08T01:10:42.107 回答