dbmitch
dbmitch

Reputation: 5386

passing directory with spaces in it from raw_input to os.listdir(path) in Python

I've looked at a few posts regarding this topic but haven't seen anything specifically fitting my usage. This one looks to be close to the same issue. They talk about escaping the escape characters.

My issue is that I want this script to run on both MAC and PC systems - and to be able to process files in a sub-folder that has spaces in the folder name.

Right now I use this code gleaned partially from several different SO posts:

directory = raw_input("Enter the location of the files: ")
path = r"%s" % directory

for file in os.listdir(path):

I don't quite understand what the second line is doing - so perhaps that's the obvious line that needs tweaking. It works fine with regular folder names but not with spaces in the name.

I have tried using "\ " instead of just " ", - that didn't work - but in any case I'm looking for a code solution. I don't want the user to have to specify an escape character

On Windoze using sub folder name "LAS Data" in response to raw_input prompt (without quotation marks), I get an message that:

the system can't find the path specified "LAS Data\*.*"

Upvotes: 0

Views: 3270

Answers (2)

Stefan Pochmann
Stefan Pochmann

Reputation: 28596

I don't quite understand what the [path = r"%s" % directory] line is doing

It creates a copy path of directory:

>>> directory = raw_input()
LAS Data
>>> path = r"%s" % directory

>>> path == directory
True

>>> type(path), type(directory)
(<type 'str'>, <type 'str'>)

Really wondering where you got that from. Seems pretty pointless.

Upvotes: 1

M. Wymann
M. Wymann

Reputation: 360

Your problem is most likely not with the code you present, but with the input you gave. The message

the system can't find the path specified "LAS Data\*.*"

suggest that you (or the user) entered the directory together with a wildcard for files. A directory with the name "LAS Data\*.*" indeed does not exist (unless you did something special to your file system :-).

Try entering just "LAS Data" instead.

The raw string should not be needed either

> python
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> directory = raw_input("Enter the location of the files: ")
Enter the location of the files: Directory with Spaces
>>> for file in os.listdir(directory):
...     print(file)
...
hello-1.txt
hello-2.txt
>>>

Upvotes: 2

Related Questions