Python 3 pywin32 saveAs功能与tkinter GUI saveas对话框路径作为输入

时间:2018-02-13 04:00:48

标签: python-3.x tkinter pywin32 win32com save-as

我是编码的完全初学者,我在解决如何使用tkinter asksavefileasname diaglog作为win32保存打开的excel文件的路径时遇到了问题。我继续收到;

  

pywintypes.com_error:(-2147352567,'发生异常。',(0,   ' Microsoft Excel'," Microsoft Excel无法访问该文件   ' C:\ //用户/用户1 /桌面/ 610D1100&#39 ;.有几种可能   原因:\ n \ n•文件名或路径不存在。\ n•文件是   被另一个程序使用。\ n•您要保存的工作簿   与当前打开的工作簿同名。",' xlmain11.chm',0,   -2146827284)

以下是相关代码:

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()

如果我手动输入保存文件的路径,它可以正常工作。

我正在尝试从saveas diaglog框中获取用户输入作为保存文件的路径。

即。 wb.SaveAs(GUI中用户输入的#path和文件名)

我没有保存已经打开的文件名。使用print时会打印正确的路径(saveFile)唯一未知的是错误消息路径中添加的\。我不确定这是否是一个tkinter问题,将\添加到路径或者这是无关紧要的。

编辑**我不认为这是一个tkinter问题,因为它适用于打印,它在错误信息中给我一个不同的文件名,这让我相信这是一个与win32相关的问题。

1 个答案:

答案 0 :(得分:1)

错误是我的变量与/而不是\作为路径分隔符返回。

wb.SaveAs只接受文件路径中的\

解决方案是使用os.path作为建议here

有关详细信息,请查看documentation

saveFile = filedialog.asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),("All files", "*.*") ))
saveFileNoSlash = os.path.normpath(saveFile)

wb.SaveAs(saveFileNoSlash)

excel.Application.Quit()

有关使用不同斜杠的问题以及使用forward替换反斜杠的其他信息,请参阅此answer