List files ONLY in the current directory

Just use os.listdir and os.path.isfile instead of os.walk.

Example:

import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
    # do something

But be careful while applying this to other directory, like

files = [f for f in os.listdir(somedir) if os.path.isfile(f)].

which would not work because f is not a full path but relative to the current dir.

Therefore, for filtering on another directory, do os.path.isfile(os.path.join(somedir, f))

(Thanks Causality for the hint)

Leave a Comment