首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python中文件路径中空格的识别

python中文件路径中空格的识别
EN

Stack Overflow用户
提问于 2022-09-14 20:17:19
回答 3查看 80关注 0票数 -1

我试图从python (jupyter记事本)打开一个文件,但是它不识别路径中的空格:

代码语言:javascript
运行
复制
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')

输出:

代码语言:javascript
运行
复制
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',它也可以工作。

EN

回答 3

Stack Overflow用户

发布于 2022-09-14 20:23:49

尝试以下操作(如果您是,则不使用):

代码语言:javascript
运行
复制
path= r"C:\Users\sam\Documents\New folder"
directory = os.path.dirname(path)
票数 0
EN

Stack Overflow用户

发布于 2022-09-14 20:43:13

鉴于您的目录中有正斜杠,我相信您只需要在目录路径上再添加一个正斜杠,如下代码段所示。

代码语言:javascript
运行
复制
import os

directory = os.path.dirname('/home/craig/Python_Programs/PathName/My Documents/')
print(directory)

这是我在终端上的测试结果。

代码语言:javascript
运行
复制
@Una:~/Python_Programs/PathName$ python3 PathName.py 
/home/craig/Python_Programs/PathName/My Documents

试试看。

票数 0
EN

Stack Overflow用户

发布于 2022-09-15 15:57:34

我找到了一个使用pathlib的解决方案,并对代码进行了如下修改-

代码语言:javascript
运行
复制
import pathlib
path = pathlib.Path(r'C:/Users/sam/Documents/New folder/testfile.docx')
document = wordapp.Documents.Open(str(path))

如果我的文件名是test file.docx,这也是有效的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73722732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档