我试图从python (jupyter记事本)打开一个文件,但是它不识别路径中的空格:
import os
import win32com.client
# Open a specified word document
wordapp = win32com.client.Dispatch('Word.Application')
# Change this depending on your file location
document = wordapp.Documents.Open('C:/Users/sam/Documents/New folder/testfile.docx')
# Gimme the links
wordapp.ActiveDocument
brokenlinks = {}
counter = wordapp.ActiveDocument.Lists(1).ListParagraphs.Count
for para in (wordapp.ActiveDocument.Lists(1).ListParagraphs):
for link in (para.Range.Hyperlinks):
try:
link.Follow()
except:
if counter in brokenlinks:
brokenlinks[counter] = brokenlinks[counter] + ", " + link.TextToDisplay
else:
brokenlinks[counter] = link.TextToDisplay
counter -= 1
# Number of broken links in the document
print('Number of footnotes with broken links:' + ' ' + str(len(brokenlinks.values())),'\n')
# Print broken links in each footnote
for i, (counter, value) in enumerate(brokenlinks.items()):
print(str(counter) + '. ' + value + '\n')
输出:
com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', "Sorry, we couldn't find your file. Was it moved, renamed, or deleted?\r (C:\\//Users/sam/Documents/New%20f...)", 'wdmain11.chm', 24654, -2146823114), None)
当我将文件夹重命名为"New_folder“时,代码可以工作。所以问题是路径中的空格。有什么办法能认出它吗?如果我的目标文件也具有空白空间,例如'C:/Users/sam/Documents/New folder/test file.docx'
,它也可以工作。
发布于 2022-09-14 20:23:49
尝试以下操作(如果您是,则不使用):
path= r"C:\Users\sam\Documents\New folder"
directory = os.path.dirname(path)
发布于 2022-09-14 20:43:13
鉴于您的目录中有正斜杠,我相信您只需要在目录路径上再添加一个正斜杠,如下代码段所示。
import os
directory = os.path.dirname('/home/craig/Python_Programs/PathName/My Documents/')
print(directory)
这是我在终端上的测试结果。
@Una:~/Python_Programs/PathName$ python3 PathName.py
/home/craig/Python_Programs/PathName/My Documents
试试看。
发布于 2022-09-15 15:57:34
我找到了一个使用pathlib
的解决方案,并对代码进行了如下修改-
import pathlib
path = pathlib.Path(r'C:/Users/sam/Documents/New folder/testfile.docx')
document = wordapp.Documents.Open(str(path))
如果我的文件名是test file.docx
,这也是有效的。
https://stackoverflow.com/questions/73722732
复制相似问题