Reputation: 23
I am a complete beginner to coding and I am having issues figuring out how to use the tkinter asksavefileasname diaglog as the path for win32 to save an open excel file. I continue to receive;
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Microsoft Excel cannot access the file 'C:\//Users/user1/Desktop/610D1100'. There are several possible reasons:\n\n• The file name or path does not exist.\n• The file is being used by another program.\n• The workbook you are trying to save has the same name as a currently open workbook.", 'xlmain11.chm', 0, -2146827284)
Here is the relevant code:
from tkinter import filedialog
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
if selection == 'Other':
wb = excel.Workbooks.Open('C:\\Users\\user1\\Desktop\\template1.xlsx')
saveFile = filedialog.asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),
("All files", "*.*") ))
print (saveFile) #This gives the correct file path
wb.SaveAs(saveFile)
excel.Application.Quit()
If I type in the path manually for savefile, it works without an issue.
I am trying to get user input from a saveas diaglog box to be the path where the file is saved.
ie. wb.SaveAs(#path and filename from user input in GUI)
I am not saving as a filename already open. The correct path prints when using print(saveFile) The only unknown is the added \ in the path from the error message. I'm not sure if this is a tkinter issue adding the \ to the path or if this is irrelevant.
Edit** I don't think this is a tkinter problem as it works with printing and it gives me a different filename in the error msg which leads me to believe this is a win32 related issue.
Upvotes: 0
Views: 1701
Reputation: 23
The error was my variable being returned with / instead of \ as path separators.
wb.SaveAs only accepts \ in file paths
The solution was to use os.path as suggested here
For more details check out the documentation
saveFile = filedialog.asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),("All files", "*.*") ))
saveFileNoSlash = os.path.normpath(saveFile)
wb.SaveAs(saveFileNoSlash)
excel.Application.Quit()
Additional information regarding issues with different slashes and replacing backslash with forward is on this answer
Upvotes: 1