Permission error when pandas dataframe is write to xlsx file

Viewed 20762

I get this error while i want to keep my dataframe in excel file which name pandas_simple.xlsx

Below is my error:

enter image description here

This is my code:

import pandas as pd
df = pd.DataFrame({'Car': [101, 20, 350, 20, 15, 320, 454]})
writer = pd.ExcelWriter('pandas_simple.xlsx')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
writer.close()

Anyone can share some idea to me here?

5 Answers

This error could also occur if you have a version of the same file (pandas_simple.xlsx in this case) already open on your desktop. In that case, python will not have permission to close and overwrite the same file as well. Closing the excel file and re-running the script should resolve the issue.

What if the path is correct?!!!

Try closing the xlsx file opened in Excel application and run the code again, it worked for me and same should happen with you.

I am attaching my code snippet for your reference


    import pandas as pd
    
    file='C:/Users/Aladahalli/Desktop/Book1.xlsx'
    xls = pd.ExcelFile(file)
    
    df = pd.read_excel(xls, sheet_name='Sheet1')
    
    #create a column by name Final and store concatinated columns
    df["Final"] = df["Name"] + "    " + df["Rank/Designation"] + "    " + df["PS"]
    print(df.head())
    
    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter('C:/Users/Aladahalli/Desktop/Final.xlsx', engine='xlsxwriter')
    
    # Convert the dataframe to an XlsxWriter Excel object.
    df.to_excel(writer, sheet_name='Sheet1')
    
    # Close the Pandas Excel writer and output the Excel file.
    writer.save()
    writer.close()

Make sure you dont have the file open that you are trying to write to.

Related