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:
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?
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.
source to share
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()
source to share