简体   繁体   中英

Store a Python output to a csv file?

I made this code where the purpose its to retrieve data from an API from a certain number of stock tickers

    import requests
    import json
    import csv
    tickers = open("ticker_list.txt","r")
    for ticker in tickers:
        ticker = ticker.strip()
        url = "https://xxx/wallstreetbets/"+ticker
        headers = {'accept': 'application'}
        r = requests.get(url, headers=headers)
        data = r.json()
        json_string = json.dumps(data, indent=1)
        for tick in data:
            print(tick ['Date'],tick['Mentions'])

This returns for every ticker an output like this

    2018-08-10 1
    2018-08-28 1
    2018-09-07 1
    2018-10-09 1
    2018-10-18 1
    2018-11-28 1
    2019-01-04 1
    2019-01-08 1
    2019-01-10 1
    2019-01-16 5
    2019-01-23 1
    2019-01-24 1

Where we have the date on the left, and the number of mentions on the right after a space.

What I want to do now is to store this result into a csv file where I have date, mentions in column so that when i open the csv file with excel I have:

    2018-08-10,1
    2018-08-28,1
    2018-09-07,1
    ...

Thanks in advance for the answers!

You can do:

import csv
.
.
.
with open('filename.csv', 'a+', newline='') as csvfile:
    fieldnames = ['Date', 'Mentions']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    for tick in data:
        writer.writerow({'Date': tick['Date'], 'Mentions': tick['Mentions']})

You can use Python3's csv.writer() function.

The given example looks like this:

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

In your specific case you would write:

import requests
import json
import csv
tickers = open("ticker_list.txt","r")
for ticker in tickers:
    ticker = ticker.strip()
    url = "https://xxx/wallstreetbets/"+ticker
    headers = {'accept': 'application'}
    r = requests.get(url, headers=headers)
    data = r.json()
    json_string = json.dumps(data, indent=1)
    
    # new code vvv
    with open("filename.csv", 'w', newline='') as csv_file:
        for tick in data:
            csv_writer = csv.writer(csv_file)
            csv_writer.writerow([tick['Date'], tick['Mentions']])

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