CSV编写器未从API调用写入新的JSON值

时间:2019-02-21 19:42:13

标签: python json api csv

我正在尝试将API调用的JSON结果保存为CSV。该API处于for循环中,它减去一天并重新运行该API以获取比特币的价格。然后应该将每个API调用保存到CSV中的一行,但是目前仅保存最后一个API调用。

如何为每个返回的API调用写一行?

import requests
import json
import csv

timestampCurrent = 1550698057
timestampOneWeekAgo = 1550161800
oneDay = 86400

for timestamp in range(timestampCurrent, timestampOneWeekAgo, -oneDay):
    print(timestamp)

    base_url = "https://api.gemini.com/v1/trades/btcusd"
    payload = {'timestamp' : timestamp,
                'limit_trades' : '1'}

    r = requests.get(url = base_url, params = payload)

    time = r.json()

    print(time)

# open a file for writing
bitcoincsv = open('/Users/kanye_west/Desktop/Code/Python/BitcoinTracker/bitcoinyear.csv', 'w')

# create csv writer object
csvwriter = csv.writer(bitcoincsv)

count = 0

for year in time:

    if count == 0:

        header = year.keys()
        csvwriter.writerow(header)
        count += 1

    csvwriter.writerow(year.values())

    bitcoincsv.close()

# append csv results
# save CSV file

1 个答案:

答案 0 :(得分:0)

这应该有效。

categoryName