1

I have a bunch of files to sort.

Im trying to get a list of names of only files (or only folders) in directory.

path = 'C:\\test\\'
items = os.listdir(path) #this gives me a list of both files and folders in dir

for name in items:
    if os.path.isfile(path + '\\' + name) == True:
        items.remove(name)

I expected that items would consist of folders' names. But it has also half of files' names.

However if I use print(name) instead of items.remove(name) it prints correctly.

Reuven Heiko
  • 21
  • 1
  • 3

2 Answers2

5

I would suspect that this is because you're changing the "items" list as you're iterating over it. It's never a good idea to do this. And this could be causing certain elements to be skipped over. That's why all files aren't being removed. Instead of the for loop, do something like this

items = [item for item in items if isfile(join(path, item))]

The join function is in os.path. And you should use that instead of adding the backslashes yourself.

Shalan
  • 176
  • 5
2

I would use os.path.isdir() in a list comprehension, like so:

For folders:

items = [f for f in os.listdir(path) if os.path.isdir( os.path.join(path, f) )]

For files:

items = [f for f in os.listdir(path) if os.path.isfile( os.path.join(path, f) )]

This builds the whole list of folders or files before starting to remove items.

Philippe Aubertin
  • 1,031
  • 1
  • 9
  • 22