Posted By: Anonymous
In Python, I only want to list all the files in the current directory ONLY. I do not want files listed from any sub directory 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, holygrail.py 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:
holygrail.py Tim Arthur Lancelot
I am happy with holygrail.py and Tim. But the two files, Arthur and Lancelot, I do not want listed.
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
(Thanks Causality for the hint)