'How do I close one specific csv file that is open in the excel application on windows using python, given the path to that file?
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!
Solution 1:[1]
You could potentially interface with Excel using a python module called xlwings
Use the API to iterate over all your open workbooks and close the ones you want by name.
pip install xlwings
import xlwings as xl
for app in xl.apps:
for book in app.books:
if book.fullname == r"your_file_path":
book.close()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vovin |
