嗨,大家好我已經把這個有用的Python腳本,讓我從一個網站獲取一些天氣數據。 我將創建一個文件和數據集indide。Python的問題:打開和關閉文件返回語法錯誤
東西不工作。它返回這個錯誤。
File "<stdin>", line 42
f.close()
^
SyntaxError: invalid syntax
怎麼了?在這一行中,我只關閉文件! 任何人都可以幫助我嗎?
這是python代碼。
import urllib2
from BeautifulSoup import BeautifulSoup
# Create/open a file called wunder.txt (which will be a comma-delimited file)
f = open('wunder-data.txt', 'w')
# Iterate through year, month, and day
for y in range(1980, 2007):
for m in range(1, 13):
for d in range(1, 32):
# Check if leap year
if y%400 == 0:
leap = True
elif y%100 == 0:
leap = False
elif y%4 == 0:
leap = True
else:
leap = False
# Check if already gone through month
if (m == 2 and leap and d > 29):
continue
elif (m == 2 and d > 28):
continue
elif (m in [4, 6, 9, 10] and d > 30):
continue
# Open wunderground.com url
url = "http://www.wunderground.com/history/airport/KBUF/"+str(y)+ "/" + str(m) + "/" + str(d) + "/DailyHistory.html"
page = urllib2.urlopen(url)
# Get temperature from page
soup = BeautifulSoup(page)
dayTemp = soup.body.nobr.b.string
# Format month for timestamp
if len(str(m)) < 2:
mStamp = '0' + str(m)
else:
mStamp = str(m)
# Format day for timestamp
if len(str(d)) < 2:
dStamp = '0' + str(d)
else:
dStamp = str(d)
# Build timestamp
timestamp = str(y) + mStamp + dStamp
# Write timestamp and temperature to file
f.write(timestamp + ',' + dayTemp + '\n')
# Done getting data! Close file.
f.close()
混合標籤和空格? – 2011-05-18 13:41:08
你代碼中的'f.close()'不在42行。準確。 – 2011-05-18 13:44:46
是的,現在代碼是正確的,我刪除了虛線。 – MrSlash 2011-05-18 14:44:43