Permission error when pandas dataframe is write to xlsx file

旧时模样 提交于 2019-12-10 19:38:17

问题


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

Below is my error:

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?


回答1:


You try to write to a folder where you need administration rights. Change:

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

to:

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

with the full path and you will not have a problem.




回答2:


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




回答3:


The documentation of pandas.DataFrame.to_excel says that the first argument can be a string that represents the file path. In your case i would drop all lines with writer and just try

df.to_excel('pandas_simple.xlsx')

That should write pandas_simple.xlsx to your current working directory. If that does not work try to provide the full path name (e.g. C:\\Users\\John\\pandas_simple.xlsx). Also make sure that you don't try to write to a directory which needs adminstration rights.




回答4:


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()



来源:https://stackoverflow.com/questions/45479110/permission-error-when-pandas-dataframe-is-write-to-xlsx-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!