I have a script that writes data to a csv file, but if that csv file is open (in the excel application on Windows 10) then it generates a PermissionError. This makes sense.
I want to be able to catch the PermissionError and then close the file down, specifically close that one csv file that is open in the excel application on Windows 10. I do NOT want to close down the entire excel application, but rather identify the specific file and then close that, leaving any other files open in excel untouched.
I have looked into using subprocess to do this, but it is not clear to me how I would achieve that. It seems like the most likely route, unless there is a better route anyone can suggest.
The ultimate code would look something like this:
import time
import pandas as pd
path_to_file = 'path/to/file.csv'
df = pd.DataFrame()
try:
df.to_csv(path_to_file) # file that is currently open
except PermissionError:
print('Shutting the Open File')
time.sleep(5)
shut_the_open_file(path_to_file) # need to figure out this code for closing the currently open file
df.to_csv(path_to_file)
Thanks!