13

I'm trying to input folder names as sys.argv arguments, but am having problem with folder names that have spaces, which become multiple variables.

For example, from the command line below, "Folder Name" becomes two variables.

Program.py D:\Users\Erick\Desktop\Folder Name 

Any solutions?

Erick Brownfield
  • 131
  • 1
  • 1
  • 6

3 Answers3

16

Space is the delimiter for command line arguments. You'll be better off not using spaces in your directory and file names if possible. For entering an argument which has space in it you'll have to enclose it in quotes "folder with space".

Program.py "D:\Users\Erick\Desktop\Folder Name"

Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
  • 1
    I am using quotes " " to separate out two input arguments (in Windows), where the first argument is a directory path. However this directory path contains a "\" at the end, which when coupled with the end quote for the python argument causes python to escape the quote and include it as part of the argument. Consequently it treats it as a single argument instead of two. Any ideas on how to un-escape the quote? – ashah Apr 20 '17 at 15:03
  • 3
    Solved it by adding an extra "\" to the end of the argument so that \ is escaped, thereby leaving the closing quote as a delimiter rather than as part of the argument itself. – ashah Apr 20 '17 at 15:06
2

Assuming input is always going to be a single file/folder path:

path = " ".join(sys.argv[1:])
Arshiyan Alam
  • 335
  • 1
  • 11
0

To extend the simplicity of Arshiyan's answer for a case involving multiple paths, you could join the paths with a delimiter such as a hash, and then split the resulting string when it gets to python...

paths = " ".join(sys.argv[1:]).split("#")
lwedwards3
  • 11
  • 1