Reuven Heiko Reuven Heiko - 11 months ago 36
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:

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

However if I use
instead of
it prints correctly.


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.