Python Forum
[SOLVED] [Windows] Right way to prompt for directory? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: [SOLVED] [Windows] Right way to prompt for directory? (/thread-37188.html)



[SOLVED] [Windows] Right way to prompt for directory? - Winfried - May-10-2022

Hello,

On Windows, I need to loop through all .TXT files in a directory.

In a command-line script (no GUI), I can't figure out how to use the user-provided directory, considering that the path could have spaces in them, in which case Windows will add double quotes before and after… but either Windows or Python removes the first double quote :-/

Also, the path could have a trailing backslash… or not.

import sys
import os
import glob

arguments = len(sys.argv) - 1
if arguments < 1:
	print ("Usage: myscript.py c:\some dir\some where\")
	exit()

src = sys.argv[1]
os.chdir(src)
"""
"c:\some dir\some where\"
becomes
c:\some dir\some where\"
"""
print(src)

for filename in os.listdir(src):
	print(filename)
Thank you.

---
Edit: I get a different output depending on if the path includes a trailing backslash or not. And obviously, not quotting a path that holds spaces isn't a good idea…

path = sys.argv[1]
print(path)
"""
c:\>myscript.py "c:\some dir\some where\"
c:\some dir\some where"

c:\>myscript.py "c:\some dir\some where"
c:\some dir\some where

c:\>myscript.py c:\some dir\some where
c:\some
"""



RE: [Windows] Right way to prompt for directory? - bowlofred - May-10-2022

This is the windows cmd shell and the odd quoting behavior it has. cmd is removing all the quotes...unless preceded by a backslash. You could just use one quote at the beginning, but no one would remember that it's okay.

You could just remove any quotes at the end. The trailing slash shouldn't matter much.

...
src = sys.argv[1].rstrip('"')



RE: [Windows] Right way to prompt for directory? - Winfried - May-10-2022

Thanks, that's what I ended up doing:

arguments = len(sys.argv) - 1
if arguments < 1:
	print ('Usage: myscript.py "c:\some dir"')
	exit()

src = sys.argv[1]
#remove double-quotes, if any
src = src.replace('"', '')

try:
	os.chdir(src)
except:
	print("Check path")
	sys.exit()
print(src)



RE: [SOLVED] [Windows] Right way to prompt for directory? - lopezmason - May-11-2022

Very good. The shares help a lot we become what we behold


RE: [SOLVED] [Windows] Right way to prompt for directory? - markoberk - Jan-17-2023

(May-11-2022, 07:18 AM)lopezmason Wrote: Very good. The shares help a lot we become what we behold

How can I find out which directory is listed in my system's pythonpath?