Recognizing whitespace in file path in python

Viewed 45

I'm trying to open a file from python (jupyter notebook) but it doesn't recognize whitespace in the path:

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

Output:

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)

The code works when I rename the folder to "New_folder". So the issue is the whitespace in the path. Is there a way to recognize it? It should also work if my target file has whitespaces too, for example, 'C:/Users/sam/Documents/New folder/test file.docx' .

3 Answers

try this (if you are NOT using the shell):

path= r"C:\Users\sam\Documents\New folder"
directory = os.path.dirname(path)

Seeing that you have forward slashes in your directory, I believe that you just need to add one more forward slash onto your directory path as in the following code snippet.

import os

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

Here was my test output in the terminal.

@Una:~/Python_Programs/PathName$ python3 PathName.py 
/home/craig/Python_Programs/PathName/My Documents

Give that a try.

I found a solution using pathlib and following changes to the code -

import pathlib
path = pathlib.Path(r'C:/Users/sam/Documents/New folder/testfile.docx')
document = wordapp.Documents.Open(str(path))

This also works if my file name is say test file.docx.

Related