slam_duncan slam_duncan - 1 year ago 95
Python Question

List files in ONLY the current directory

In Python, I only want to list all the files in the current directory ONLY. I do not want files listed from any subdirectory or parent.

There do seem to be similar solutions out there, but they don't seem to work for me. Here's my code snippet:

import os
for subdir, dirs, files in os.walk('./'):
for file in files:
do some stuff
print file

Let's suppose I have 2 files, and Tim inside my current directory. I have a folder as well and it contains two files - let's call them Arthur and Lancelot - inside it. When I run the script, this is what I get:

I am happy with and Tim. But the two files, Arthur and Lancelot, I do not want listed.

Answer Source

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


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)