Permission error when pandas dataframe is writing to xlsx file

I am getting this error while I want to save my data file in an excel file called 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()

      

Can anyone share some ideas with you here?

+3


source to share


4 answers


You are trying to write to a folder where you need administrator rights. Change:

writer = pd.ExcelWriter("pandas_simple.xlsx")

      

in



writer = pd.ExcelWriter("C:\\...\\pandas_simple.xlsx")

      

with a full path and you won't have any problems.

+5


source


The pandas.DataFrame.to_excel documentation says that the first argument can be a string representing the file path. In your case, I would dump all lines with a write and just try

df.to_excel('pandas_simple.xlsx')

      



This should write pandas_simple.xlsx to the current working directory. If that doesn't work, try specifying the fully qualified pathname (for example, C: \\ Users \\ John \\ pandas_simple.xlsx). Also make sure you are not trying to write to a directory that requires administrator rights.

+1


source


This error can also occur if a version of the same file (in this case pandas_simple.xlsx) is already open on your desktop. In this case, python will not have the right to close and overwrite the same file. Closing the Excel file and rerunning the script should fix the problem.

0


source


What if the path is correct? !!!

Try to close the xlsx file open in Excel application and run the code again, it works for me and the same should happen to 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()


      

0


source







All Articles