fazineroso
fazineroso

Reputation: 7466

I want to have a list of subdirectories and then print it

I am very new to python, so sorry in advance if this question is too basic.

I want to read a list of subdirectories of a path and then print it. But instead of printing the names of the subdirectories it prints the characters:

products = []
dir_path = "/tmp"
for item in os.listdir(dir_path):
    products.extend(item)
index = 0
for product in products:
    print "%d %s" % ((index+1),product)
    index += 1

what I am doing wrong here?

Upvotes: 0

Views: 72

Answers (4)

user1251007
user1251007

Reputation: 16721

You need to add the item to your list.

products.add(item)

extend adds all the items (characters in your case) of any iterable (the path) to a list.

Upvotes: 0

Deck
Deck

Reputation: 1979

The first thing I would point is

products.extend(item)

extends method extends the list by appending all the items in the given list. Since strings are iterable objects you just add all chars to the list. Change the method to append

The second thing is if you want to get an element and its index in a loop use enumerate method. Don't use counter variables.

for index, item in enumerate(products):
    print "%d %s" % (index, item)

And the last.
os.listdir returns the all entries from specified directory. If you want to get subdirectories only

products = (d for d in os.listdir('.') if os.path.isdir(d))
for i, product in enumerate(products):
    print "{0} {1}".format(i, product)

Upvotes: 1

Guy Gavriely
Guy Gavriely

Reputation: 11396

[(idx, f) for idx, f in enumerate(os.listdir('.'))]

EDIT (as suggested by @DSM):

list(enumerate(os.listdir('.')))

Upvotes: 2

Peter Westlake
Peter Westlake

Reputation: 5036

You are using extend, which takes an iterable and adds each element of it to a list, instead of append, which just adds the argument you pass to it. Like this:

>>> a = [1,2]
>>> a.extend([3,4])
>>> a
[1, 2, 3, 4]
>>> b = [1,2]
>>> b.append([3,4])
>>> b
[1, 2, [3, 4]]

A string behaves like a list of characters. So extend adds each character of the item instead of the item itself.

You don't need to use a loop to construct a list, because os.listdir will return one anyway:

products = os.listdir(dir_path)

And you can write the second loop without incrementing the index yourself:

for idx, product in enumerate(products):
    print "%d %s" % ((index+1),product)

The enumerate function produces an object which generates just the pairs of (index, listitem) that you need.

Upvotes: 2

Related Questions