2012-11-08 37 views
1

我正在使用python和simplekml創建者創建kml文件。 由於某些原因,它創建了兩個kml文件,並且不會創建第三個文件。數據對我來說似乎很好。下面是代碼:使用python創建kmls時遇到問題

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語句,無論我穿什麼爲了他們,這將爲鋼鐵希爾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 

錯誤消息調出什麼如果語句是最上面。我難倒了。希望我的問題是有道理的(它爲什麼不給我這個錯誤消息,並且只創建兩個的KML無論什麼樣的順序if語句中)

回答

0

變化

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

到:

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

在你的第一行添加一個

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

確保你有足夠的線...

更新

你回溯(在評論)說明你的(1?)dayoftheweek似乎是一個星期三,這就是爲什麼你的第一雙中頻被忽略。那麼看起來好像你的名單a沒有nough條目。

您可以檢查這個假設有print("# a: {0}".format(len(a)))

所以,如果你有少於3項a[2]==一定會失敗,因爲list index out of range ;-)

啊,我沒有正確的第一次讀你的問題。而更有意義的是這樣,如果每1 if語句是拋出一個異常....

更新2: 順便說一句:你應該rearange您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:

如果ommiting一些線條,通過做一些像你可以 「騙」 了一點:

a = line.split(',') 
if len(a) < 6: 
    continue # ignores the rest of the loop and jumps stright to the next iteration 
+0

這是我爲您編輯了:#Times:1048 週三 回溯(最近通話最後一個): 文件 「C:/用戶/ 75IV740906 /桌面/ py117」 28行,在 如果a [1] ==「Limoncello」和[2] ==「Wednesday」: IndexError:列表索引超出範圍 – user1807770

+0

這次沒有創建任何kmls,但似乎有足夠的行 – user1807770

+0

行就夠了,但是每行都有足夠的記錄...我會詳述一個更新的答案 –