Python Forum
[SOLVED] [Windows] Right way to prompt for directory?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] [Windows] Right way to prompt for directory?
#1
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
"""
Reply


Messages In This Thread
[SOLVED] [Windows] Right way to prompt for directory? - by Winfried - May-10-2022, 06:47 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  'pip' not recogmnized in windows prompt MaartenRo 1 507 Dec-21-2023, 09:05 AM
Last Post: menator01
  working directory if using windows path-variable chitarup 2 869 Nov-28-2023, 11:36 PM
Last Post: chitarup
  [SOLVED] [Windows] Fails reading strings with accents Winfried 1 913 Apr-23-2023, 05:27 PM
Last Post: Larz60+
  [SOLVED] [Windows] Converting filename to UTF8? Winfried 5 2,875 Sep-06-2022, 10:47 PM
Last Post: snippsat
  Open windows cmd prompt and run cmds with python Extra 3 1,588 Jul-14-2022, 06:07 AM
Last Post: Gribouillis
  No Module found in other directory than source code [SOLVED] AlphaInc 1 2,191 Nov-10-2021, 04:34 PM
Last Post: AlphaInc
  starting python from windows command prompt MaartenRo 4 2,968 Sep-04-2020, 12:25 PM
Last Post: MaartenRo
  Need info for getting directory content in Windows wlathan 2 2,037 May-20-2020, 12:40 PM
Last Post: wlathan
  Subprocess command prompt (Windows) arnaur 6 10,648 Sep-06-2018, 07:22 AM
Last Post: arnaur
  SOLVED: best way to block (wait on) shell calls to multiple windows programs at once? ezdev 0 2,676 Dec-10-2017, 06:42 AM
Last Post: ezdev

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020