Python problem: opening and closing a file returns a syntax error

痞子三分冷 提交于 2020-01-05 02:36:14

问题


Hi guys I've fonund this useful python script that allows me to get some weather data from a site. I'm going to create a file and the dataset indide.

Something is not working. It returns this error.

File "<stdin>", line 42
     f.close()
     ^
SyntaxError: invalid syntax

What's wrong? In this line I'm only closing the file! Could anyone help me please?

This is the python code.

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

回答1:


Looks like you have a whitespace problem in there. Check the whitespace of the file - see where spaces and tabs are. If there are both tabs and spaces in the file, convert them all to spaces.

f.close should be at the same indentation level as f = open('wunder-data.txt', 'w')




回答2:


The line with the f.close() isn't line 42, so are you sure this is the code that gives the error?

Also, Python seems to process a program received on stdin, is this your intention?




回答3:


Delete lines in your code until the syntax error goes away. Then you'll be able to narrow the problem.



来源:https://stackoverflow.com/questions/6045605/python-problem-opening-and-closing-a-file-returns-a-syntax-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!