大家好,我有一个语法错误,我真的不明白......任何人都可以帮忙吗? 我在控制台上收到此消息:
File "./data_4.0.1.py", line 170
elif:
^
SyntaxError: invalid syntax
此elif上出现错误:
#controllo ultimo timestamp
elif:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
这是我的代码:
def funzione_aggiornamento_prezzi(titolo,timeframe,lookback):
#parametri per scaricare lo storico dei prezzi
if timeframe =='TBT':
lookback = 0
elif timeframe =='1M':
lookback = 7
elif timeframe =='5M':
lookback = 60
elif timeframe =='60M':
lookback = 180
elif timeframe =='1D':
lookback = 1800
params = {'item': titolo,
'frequency': timeframe,
'dataDa':x_giorni_fa(lookback)}
try:
r = requests.get(myurl, params=params)
except:
pprint("Si e' verificato un errore")
else:
pprint(r.status_code)
pprint(r.url)
new_list = crea_lista(r)
#codice per scrivere su di un csv da una lista
nomen = "%s.%s.csv" % (titolo,timeframe)
csvfile = open(nomen, 'a')
reportwriter = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
#codice per scrivere su di un csv
#controllo del numero di rows nel file
with open(nomen,"r") as f:
reader = csv.reader(f,delimiter = ",")
data = list(reader)
row_count = len(data)
if row_count == 0:
for i in new_list:
da_appendere = i
reportwriter.writerow(da_appendere)
csvfile.close()
#controllo ultimo timestamp
elif:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
#codice per appendere solo i nuovi dati
found_it = 0
for i in range((len(new_list))-1):
if new_list[i] == last_timestamp:
found_it = 1
if found_it == 1:
this_elem = new_list[i]
next_elem = new_list[(i+1)]
#print(this_elem)
#print(next_elem)
da_appendere1 = next_elem
reportwriter.writerow(da_appendere1)
csvfile.close()
for i in lista_indici:
for j in lista_timeframe:
funzione_aggiornamento_prezzi(i,j,lookback)
答案 0 :(得分:1)
当你将指令放在与if
语句相同的级别缩进
if condition:
stuff
something # doing this close the if block
和elif
只能在if块中发生
你在
中这样做 if row_count == 0:
for i in new_list:
da_appendere = i
reportwriter.writerow(da_appendere)
csvfile.close() #<-- here you close the if block
#controllo ultimo timestamp
elif: #<-- you forgot the condition, and is outside of a 'if' block
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
此外,如果您不需要使用elif
而忘记在else
中添加条件
答案 1 :(得分:0)
如果您没有其他if
声明,则应使用else
代替elif
。
请参阅有关控制流的documentation。