Reputation: 3
I have the following code:
def get_asset_info(asset_list):
import datetime
today = datetime.datetime.today()
day = today.strftime("%d")
for i in range( len( asset_list )):
raw_info = get_OHLC( asset_list[i], 15, get_server_time() )
info = raw_info['result'][asset_list[i]]
head = "time,open,high,low,close,vwap,volume,count"
formatted_info = ""
for i in range(len(info[0])):
formatted_info = formatted_info + info[0][i] + ","
file = open(asset_list[i]+"_"+day, "a")
file.write(head + "\n")
file.write(formatted_info)
file.close()
It is supposed to get some values, convert it into a string and write it to a file, dynamically generated. It's not working like this and all the values are put in the same file.
If I change the last part of the code like the following, the files are generated:
formatted_info = str(info[0][0]) + "," + str(info[0][1]) + "," + str(info[0][2]) + "," + str(info[0][3]) + "," + str(info[0][4]) + "," + str(info[0][5]) + "," + str(info[0][6]) + "," + str(info[0][7])
file = open(asset_list[i]+"_"+day, "a")
file.write(head + "\n")
file.write(formatted_info)
file.close()
So the problem, as I can see, is in the for loop I create to generate my string, but there's no sense since the code that generates the file is not in the same loop.
Any ideas?
Upvotes: 0
Views: 76
Reputation: 56477
for i in range( len( asset_list )):
...
for i in range(len(info[0])):
...
# now what do you think i is now?
file = open(asset_list[i]+"_"+day, "a")
Changing second i
to j
should do the trick:
for i in range( len( asset_list )):
...
for j in range(len(info[0])):
formatted_info = formatted_info + info[0][j] + ","
file = open(asset_list[i]+"_"+day, "a")
or even better:
for i in range( len( asset_list )):
...
for piece in info[0]:
formatted_info = formatted_info + str(piece) + ","
file = open(asset_list[i]+"_"+day, "a")
or finally better:
for i in range( len( asset_list )):
...
formatted_info = ','.join(str(obj) for obj in info[0]) + ','
file = open(asset_list[i]+"_"+day, "a")
Upvotes: 2