When i want to run my python script i get this error:
File "", line 4 f.close ^ SyntaxError: invalid syntax
Got the error at this section:
#read ticker symbols from a file to python list object named symbol
symbol = []
with open(r'C:/Users/nassir005/Documents/python/ExhangeSymbols.csv') as f:
for line in f:
symbol.append(line.strip())
f.close
I have included the whole code below:
#settings for importing built-in datetime and date libraries
#and external pandas_datareader libraries
import pandas_datareader.data as web
import datetime
import os
os.chdir(r'C:\Users\nassir005\Documents\python')
#read ticker symbols from a file to python list object named symbol
symbol = []
with open(r'C:/Users/nassir005/Documents/python/ExhangeSymbols.csv') as f:
for line in f:
symbol.append(line.strip())
f.close
#datetime is a Python module
#datetime.date is a data type within the datetime module
#the start expression is for January 1, 2009
start = datetime.date(2009,1,1)
#the end expression is for October 7, 2019
end = datetime.date(2019,10,7)
#set path for csv file
path_out = 'C:/Users/nassir005/Documents/python/ouput'
file_out = 'yahoo_prices_volumes_for_ExchangeSymbols_from_01012009_07102019.csv'
#loop through tickers in symbol list with i values of 0 through
#index for last list item
#if no historical data returned on any pass, try to get the ticker data again
#if destination file is open in Excel, close Excel and continue data collection
#quit retries to get historical data for a symbol after tenth retry
i=0 #pointer for symbol
j=0 #count for loop within symbol
while i<len(symbol):
try:
df = web.DataReader(symbol[i], 'yahoo', start, end)
df.insert(0,'Symbol',symbol[i])
df = df.drop(['Adj Close'], axis=1)
print ('from after dr', i,j, symbol[i])
if i == 0:
df.to_csv(path_out file_out)
else:
df.to_csv(path_out file_out,mode = 'a',header=False)
j=0
except:
print ('from except', i,j, symbol[i])
if j <=9:
print(i, symbol[i], j,'Eligible for retry')
j = j 1
continue
if j == 10:
j=0
i=i 1
continue
i=i 1
Could somebody please help me with this issue?
Thank you.
Kamval
CodePudding user response:
Close is a function, not an attribute, so you have to type f.close()
, instead of f.close
.
Generally, in python, all functions call must have parentheses after the name, even if empty. Inside parentheses you can pass the arguments to be used inside the function.
If you don't have parentheses it means that you are accessing an attribute inside an object.
In this case close
is a function, so the parentheses are needed.
CodePudding user response:
i have added f.close(), but it returns invalid syntax..
import pandas_datareader.data as web
import datetime
import os
os.chdir(r'C:\Users\nassir005\Documents\python')
#read ticker symbols from a file to python list object named symbol
symbol = []
with open(r'C:/Users/nassir005/Documents/python/ExhangeSymbols.txt') as f:
for line in f:
symbol.append(line.strip())
f.close()