NUMB
NUMB

Reputation: 43

Writing CSV file Python3 issue

I'm using poloniex trader api to get realtime market ticker info. It works perfect on console. When ever i request for market ticker in returns i get this {'last': '0.07269671', 'high24hr': '0.07379970', 'quoteVolume': '71582.56540639', 'isFrozen': '0', 'lowestAsk': '0.07277290', 'percentChange': '-0.00551274', 'id': 148, 'low24hr': '0.07124645', 'highestBid': '0.07269671', 'baseVolume': '5172.41552885'}

Problem is it's only storing item name/list name such as - low24hr, lowestAsk, highestBid etc. Not their value like -low24hr : 0.07124645

polo = Poloniex()
ticker_data = (polo('returnTicker')['BTC_ETH'])

out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL,)
out.writerow(ticker_data)
print(ticker_data)

Here is what my csv file looks like- ImageView

ImageView

Upvotes: 1

Views: 85

Answers (2)

skrx
skrx

Reputation: 20438

Your problem is that out.writerow(ticker_data) takes only the keys of the dictionary and writes them to the file. Try to use a csv.DictWriter:

with open('myfile.csv', 'w', newline='') as csv_file:
    # Pass the keys of the `ticker_data` as the fieldnames.
    writer = csv.DictWriter(csv_file, fieldnames=ticker_data, quoting=csv.QUOTE_ALL)
    # Write the fieldnames.
    writer.writeheader()
    # Write the values.
    writer.writerow(ticker_data)

Upvotes: 1

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

with open('my_file.csv', 'w') as f:
    for key, value in ticker_data.items(): f.write('{0},{1}\n'.format(key, value))

From here.

Upvotes: 1

Related Questions