I'm trying to load data to a panda dataframe from an existing Excel-file, "file1", do some modifications to it, and then export the dataframe to a new sheet in the same workbook ("file1"). My code works fine when "file1" is closed, but if I have the file open in Excel at the same time as I run my code, I get the error: PermissionError: [Errno 13] Permission denied. What is the issue here? is Python not able to save a workbook which is simultaneously open in Excel, or are there any workarounds here?
This is my code:
import pandas as pd
from openpyxl import load_workbook
#Read the input data to a panda dataframe
df = pd.read_excel(workbook_path, sheet_name = 'input_data')
---Do stuff to the dataframe--
#Access the existing excel-file
workbook = load_workbook(workbook_path)
#Create a writer-object
writer = pd.ExcelWriter(workbook_path, engine = 'openpyxl')
writer.book = workbook
#Create a new sheet called "Results"
df.to_excel(writer,sheet_name = 'Results')
#Save the workbook
writer.save()
writer.close()