moot3ch
moot3ch

Reputation: 45

Python: list directory using user input as directory name not working

I've been trying to solve this problem all day. I just want to list the files within a directory that a user will specify. Below is my code and traceback:

>>> os.listdir(r'{}'.format(input('directory:')))

directory:C:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 123] The filename, directory name, or volume label syntax i
s incorrect: 'C:\r\\*.*'

Any help would be greatly appreciated, thank you!

Upvotes: 0

Views: 2555

Answers (3)

RanRag
RanRag

Reputation: 49547

You need to give C: in string format.

Its working fine for me

>>> os.listdir(r'{0}'.format(input('directory:')))
directory:"C:\Users"
['All Users', 'Default', 'Default User', 'desktop.ini', 'Public', 'RanRag']
>>>

or try using raw_input.

>>> os.listdir(r'{0}'.format(raw_input('directory:')))
directory:C:\Users
['All Users', 'Default', 'Default User', 'desktop.ini', 'Public', 'RanRag']

The raw_input function reads a line from input, converts it to a string (stripping a trailing newline), and returns that

If you are using python3 than raw_input is replaced by input.

>>> os.listdir(r'{0}'.format(input('directory:')))
directory:C:\Users
['All Users', 'Default', 'Default User', 'desktop.ini', 'Public', 'RanRag']
>>>

Upvotes: 3

Smoe
Smoe

Reputation: 1550

As RanRag said. But since you'll already get a string from raw_input you can do it like this:

os.listdir(raw_input('directory: '))

Upvotes: 0

Pit
Pit

Reputation: 4046

I guess that the error lies in the use of input instead of raw_input.

If you use input python tries to parse the text the user entered. In your case you just want to have the string the user enters, so you either have to add quotes to the string (like RanRag did in his answer), or you could simply use raw_input as it returns the characters the user typed as a string.

Upvotes: 2

Related Questions