"File Not Found" Trying To Listdir() A Path Dragged-and-dropped From Finder To Terminal In Python

- 1 answer

after researching this error the solution most suggested is to use absolute path instead of relative (which makes sense and obvious)
however this doesnt work in macos.
and I thought python works on all platforms the same
my code:

import os
directory = input("insert path: ")
for filename in os.listdir(directory):
    f = os.path.join(directory, filename)
    if os.path.isfile(f):

once I run this I get a prompt asking me to insert the directory path. so I drag and drop the directory and the absolute path is inserted.
right after I hit enter. I get the famous error file or directory not found. any help ?



When I run your code and drag a folder from finder into the (iterm2) terminal window, it inserts a space after the path, probably to be helpful in case you want to pass other arguments to a shell, which would be space separated. Remove the space manually before hitting enter, and it should work.

When the path you drag in has spaces, Finder seems to try to quote these spaces, e.g., foo bar becomes foo\ bar. Again this makes sense for a shell, where spaces can be escaped like this, but your Python program is not a shell, so you'd check for \ and replace it with a plain again:

directory = directory.replace(r"\ ", " ")

And if you want to do that kind of processing, you could also remove the trailing space for better usability:

directory = directory.strip()