Python问题:打开和关闭文件返回语法错误 [英] Python problem: opening and closing a file returns a syntax error

查看:36
本文介绍了Python问题:打开和关闭文件返回语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我找到了这个有用的 python 脚本,它允许我从站点获取一些天气数据.我将创建一个文件和数据集.

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?

这是python代码.

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

推荐答案

看起来您在那里遇到了空格问题.检查文件的空格 - 查看空格和制表符的位置.如果文件中同时存在制表符和空格,请将它们全部转换为空格.

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 应该与 f = open('wunder-data.txt', 'w')

这篇关于Python问题:打开和关闭文件返回语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆