简体   繁体   中英

Writing a CSV File Using Data from an API in Python

I'm learning Python and decided to play around a bit with a project that I've been wanting to tackle for a while now. I ended up trying to use an API that returns data that I would like to write to a CSV file. I'm struggling with how to parse that out given the formatting of the data, though. I used the following lines to grab the data in question. How can I take that data (shortened version shown below the code) and parse that into a CSV file?

    from pycoingecko import CoinGeckoAPI
    import pandas as pd

    cg = CoinGeckoAPI()

    data = cg.get_coin_market_chart_by_id('bitcoin', 'usd', 'max')
    print(data)

{'prices': [[1367107200000, 135.3], [1367193600000, 141.96], [1367280000000, 135.3], [1367366400000, 117.0], [1367452800000, 103.43], [1367539200000, 91.01], [1367625600000, 111.25], [1367712000000, 116.79], [1367798400000, 118.33], [1367884800000, 106.4], [1367971200000, 112.64]]}

I'd recommend using pandas . Note that in the following snippet just uses the default options for to_csv() , but you can customize it quite a lot to suit your needs.

import pandas as pd
data = {'prices': [[1367107200000, 135.3], [1367193600000, 141.96], [1367280000000, 135.3], [1367366400000, 117.0], [1367452800000, 103.43], [1367539200000, 91.01], [1367625600000, 111.25], [1367712000000, 116.79], [1367798400000, 118.33], [1367884800000, 106.4], [1367971200000, 112.64]]}
df = pd.DataFrame.from_dict(data['prices'])
df.to_csv('test.csv')

or try something like that:

import csv

a = {'prices': [[1367107200000, 135.3], [1367193600000, 141.96], [1367280000000, 135.3], [1367366400000, 117.0], [1367452800000, 103.43], [1367539200000, 91.01], [1367625600000, 111.25], [1367712000000, 116.79], [1367798400000, 118.33], [1367884800000, 106.4], [1367971200000, 112.64]]}

with open('new_file.csv', 'w+') as f:
    writer = csv.writer(f)
    for line in a.get('prices'):
        writer.writerow(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM