Search code examples
pythonpandasdataframeexport-to-csv

Python AttributeError: 'list' object has no attribute 'to_csv'


I'm currently encountering an error with my code, and I have no idea why. I originally thought it was because I couldn't save a csv file with hyphens in it, but that turns out not to be the case. Does anyone have any suggestions to what might be causing the problem. My code is below:

import pandas as pd
import requests

query_set = ["points-per-game"]

for query in query_set:
    url = 'https://www.teamrankings.com/ncaa-basketball/stat/' + str(query)
    html = requests.get(url).content
    df_list = pd.read_html(html)
    print(df_list)

    df_list.to_csv(str(query) + "stat.csv", encoding="utf-8")

Solution

  • the read_html() method returns a list of dataframes, not a single dataframe:

    https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_html.html

    You'll want to loop through your df_list and run to_csv on each entry, like so:

    import pandas as pd import requests
    
    query_set = ["points-per-game"]
    
    for query in query_set:
        url = 'https://www.teamrankings.com/ncaa-basketball/stat/' + str(query)
        html = requests.get(url).content
        df_list = pd.read_html(html)
        print(df_list)
    
        for current_df in df_list:
          current_df.to_csv(str(query) + "stat.csv", encoding="utf-8")
          print(current_df)