"File Not Found" Trying To Listdir() A Path Dragged-and-dropped From Finder To Terminal In Python
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
#!/usr/bin/python3 import os directory = input("insert path: ") for filename in os.listdir(directory): f = os.path.join(directory, filename) if os.path.isfile(f): print(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
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()
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module