Python的开场白,意外行为

Python的开场白,意外行为,python,python-2.7,ms-word,Python,Python 2.7,Ms Word,我正在编写一个脚本来解析word文档并获得某些输出。我使用以下命令读取所需的文档 import win32com.client as win32 import Tkinter,tkFileDialog root = Tkinter.Tk() root.withdraw() filename = tkFileDialog.askopenfilename() # getting filename through windows explorer word = win32.Dispatch("W

我正在编写一个脚本来解析word文档并获得某些输出。我使用以下命令读取所需的文档

import win32com.client as win32
import Tkinter,tkFileDialog

root = Tkinter.Tk()
root.withdraw()

filename = tkFileDialog.askopenfilename() # getting filename through windows explorer

word = win32.Dispatch("Word.Application")
#word.Documents.Open(filename)
评论的最后一行是我计划如何实现这一点。但每当我试图打开一个文件名中有空格的文件时,就会失败。事实上,我发现如果我给出
word.Documents.Open(“C:/Python27/word-sample.docm”)
这也会失败,但如果我在
C:
之后使用反斜杠,它会工作得很好

简而言之,以下用于打开文档的命令将起作用:

word.Documents.Open("C:\Python27/word sample.docm")
word.Documents.Open(filename) #if filename don't have a space
而以下各项将不起作用:

word.Documents.Open("C:/Python27/word sample.docm")
word.Documents.Open(filename) #filename have a space in it
有人能解释一下这里出了什么问题吗

这是我收到的错误:

C:\Users\xxx>C:\Python27\python.exe C:\Python27\test.py
Traceback (most recent call last):
  File "C:\Python27\test.py", line 10, in <module>
    word.Documents.Open("C:/Python27/word sample.docm")
  File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Word'
, u'This file could not be found.\r (C:\\//Python27/word%20sample.docm)', u'
wdmain11.chm', 24654, -2146823114), None)
C:\Users\xxx>C:\Python27\python.exe C:\Python27\test.py
回溯(最近一次呼叫最后一次):
文件“C:\Python27\test.py”,第10行,在
word.Documents.Open(“C:/Python27/word-sample.docm”)
文件“”,第8行,处于打开状态
pywintypes.com_错误:(-2147352567,'发生异常',(0,u'Microsoft Word'
,u'找不到此文件。\r(C:\\//Python27/word%20sample.docm)',u'
wdmain11.chm',24654,-2146823114),无)

在将文件名传递到windows之前,您是否尝试过在文件名上使用
os.path.normpath(…)
?谢谢!!我想它起作用了。您能简单地说一下我做错了什么吗?在将文件传递到windows之前,您是否尝试过在文件名上使用
os.path.normpath(…)
?谢谢!!我想它起作用了。你能简单地说一下我做错了什么吗。