Python问题:打开和关闭文件返回语法

2024-05-19 07:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好,我喜欢这个有用的python脚本,它允许我从一个站点获取一些天气数据。 我要创建一个文件和数据集indide。

有东西坏了。它返回此错误。

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()

Tags: andinurlforifrangeelsetimestamp
3条回答

删除代码中的行,直到语法错误消失。这样你就能缩小问题的范围。

带有f.close()的行不是第42行,所以您确定这是导致错误的代码吗?

另外,Python似乎处理在stdin上接收到的程序,这是您的意图吗?

你好像有个空格问题。检查文件的空白-查看空格和制表符的位置。如果文件中同时有制表符和空格,请将它们全部转换为空格。

f.close应与f = open('wunder-data.txt', 'w')处于相同的缩进级别

相关问题 更多 >

    热门问题