I have a directory and need to get all files in it, but not subdirectories.
I have found os.listdir(path)
but that gets subdirectories as well.
My current temporary solution is to then filter the list to include only the things with '.' in the title (since files are expected to have extensions, .txt and such) but that is obviously not optimal.
Asked
Active
Viewed 65 times
-2
-
1Or even this https://stackoverflow.com/questions/14176166/list-only-files-in-a-directory. Seeing as this questions title is basically identical to yours, please read [how much research is expected](https://meta.stackoverflow.com/q/261592/843953) – Pranav Hosangadi Dec 22 '22 at 18:31
-
`os.listdir()` does not include subdirectories (as in: it does not list directories recursively). It does, however, include all files and directories in the current directory. Is that what you mean? – wovano Dec 22 '22 at 18:34
1 Answers
-1
We can create an empty list called my_files and iterate through the files in the directory. The for loop checks to see if the current iterated file is not a directory. If it is not a directory, it must be a file.
my_files = []
for i in os.listdir(path):
if not os.path.isdir(i):
my_files.append(i)
That being said, you can also check if it is a file instead of checking if it is not a directory, by using if os.path.isfile(i)
.
I find this approach is simpler than glob because you do not have to deal with any path joining.

stapmoshun
- 88
- 1
- 7
-
2Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Dec 24 '22 at 00:27