Reuven Heiko Reuven Heiko - 5 months ago 11
Python Question

How to create list of files in directory in Python

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.

Answer

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.

Comments