Search code examples
pythonlistdataframenames

elements from a list to dataframe names for export


I have a list of names of dataframes

list = ['one','two','three','four']

and I want to export them:

for i in range (0,len(list)):
    with pd.ExcelWriter(output_path + '//' + 'file'+i+'.xlsx') as writer:
    list[i].to_excel(writer, index=False)

it shows this error: AttributeError: 'str' object has no attribute 'to_excel'

basically i need:

for i in range (0,len(list)):
    with pd.ExcelWriter(output_path + '//' + 'file1'.xlsx') as writer:
    one.to_excel(writer, index=False)

and do it for all element in the list


Solution

  • Having a list

    list_of_dfs = [df0, df1, df2]
    

    I created a dictionary with the dataframes (this is the key):

    UniqueSource = df_raw.Key.unique()
    DataFrameDict = {elem : pd.DataFrame for elem in UniqueSource}
    for key in DataFrameDict.keys():
        DataFrameDict[key] = df_raw[:][df_raw.Key == key]
    

    Then I created a list of all files in the path:

    outlib = os.listdir(output_lib)
    outlib_names = [s.replace(".xls","") for s in outlib]
    

    And finally by checking each one of the list_of_dfs in the outlib_names, I created a temp dataframe out of the dictionary, it file already exist it will open the file and export the data frame into a sheet, else if the file doesn't exist it will simple just export the data frame as a new file in the path:

    for f in list_of_dfs:
            check = (f in outlib_names)
            if check is True:
                temp = DataFrameDict[f]
                with pd.ExcelWriter(output_lib + "\\" + f + '.xlsx', engine='openpyxl', mode='a') as writer:
                    temp.to_excel(writer, sheet_name = "'" + f "'", index = False)
            else:
                temp = DataFrameDict[f]
                with pd.ExcelWriter(output_lib + "\\" + f + '.xlsx') as writer:
                    temp.to_excel(writer, sheet_name="'" + f + "'", index=False)