Reputation: 152
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()
Upvotes: 2
Views: 31365
Reputation: 1
I had the same problem today 2020(October), and I just checked the code above the close() function. I found I hadn't closed a bracket earlier. So the error is in the code above the function and not the actual line specified.
Upvotes: 0
Reputation: 512
I had a similar Error showing syntax error in 3.8 just now. And it turns out, my syntax error was a missing closing parenthesis in code above the highlighted line. So, line 42 is not what Question Putter should be looking at. Perhaps, there is actually a syntax error somewhere above in the code.
Upvotes: 1
Reputation: 45039
Delete lines in your code until the syntax error goes away. Then you'll be able to narrow the problem.
Upvotes: 0
Reputation: 229593
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?
Upvotes: 0
Reputation: 273446
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')
Upvotes: 4