Python data output to Excel

Viewed 375

While spending hours attempting to figure out ways to import stats to an Excel file I came across a version of this script that I've attempted to use in Python. When executing I get the following error below the second csv_output portion of the script:

KeyError: 0

I'm just beginning to learn the nuances of Python and can't really figure out what I'm doing wrong here.

I'm currently using Python 3.6 and Windows 10. Any help would be greatly appreciated.

import requests
import csv

url = "http://stats.nba.com/stats/leagueLeaders?
LeagueID=00&PerMode=PerGame&Scope=S&Season=2017-
18&SeasonType=Regular+Season&StatCategory=PTS"

data = requests.get(url, timeout=5)
entries = data.json()

with open('output.csv', 'w') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(entries['resultSet'][0]['headers'])
    csv_output.writerows(entries['resultSet'][0]['rowSet'])
3 Answers
  1. I dont see a module named requests. Perhaps try urllib.request.urlopen(url, timeout=5)

  2. The URL is not correct. If you just open using your browser, it leads to a error. Perhaps check your URL again.

entries['resultset'] is a dict object and it doesn't have '0' key. It has only 'headers', 'rowset', 'name'.

Just remove '[0]' from the below two lines of code, this will work.

    csv_output.writerow(entries['resultSet']['headers'])
    csv_output.writerows(entries['resultSet']['rowSet'])

This solution worked for me:

  import pandas as pd
    data = requests.get(url, timeout=5)
    entries = data.json()
    Header=entries['resultSet']['headers']
    data =entries['resultSet']['rowSet']
    filename='c:\\test\\NBA.xlsx'           

    df = pd.DataFrame.from_records(data)    
    df.columns=Header
    writer = pd.ExcelWriter(filename, engine='xlsxwriter')
    df.to_excel(writer, sheet_name='sheet1', index=False,startrow=0 , startcol=0)
    writer.save()
Related