Is it possible to see files with certain extensions with the os.listdir command? I want it to work so it may show only files or folders with .f at the end. I checked the documentation, and found nothing, so don't ask.
Asked
Active
Viewed 2.1k times
5 Answers
24
glob
is good at this:
import glob
for f in glob.glob("*.f"):
print(f)

Yui
- 57
- 2
- 9

Ned Batchelder
- 364,293
- 75
- 561
- 662
-
+1 wow, that helped a lot! But cant we just do print(glob.glob("*.py")) ? – Galilsnap Jun 26 '10 at 02:55
-
2You can do that, glob.glob returns a list, do what you want with it. – Ned Batchelder Jun 26 '10 at 03:14
20
Don't ask what?
[s for s in os.listdir() if s.endswith('.f')]
If you want to check a list of extensions, you could make the obvious generalization,
[s for s in os.listdir() if s.endswith('.f') or s.endswith('.c') or s.endswith('.z')]
or this other way is a little shorter to write:
[s for s in os.listdir() if s.rpartition('.')[2] in ('f','c','z')]

David Z
- 128,184
- 27
- 255
- 279
-
There are a lot of things that are explicit function calls in other languages that are replaced by built-in operations in Python. It's tricky keeping track sometimes. For example, the various adapter templates in C++ standard library are simply `lambda` in Python. It's one of my favorite things about Python. – Mike DeSimone Jun 26 '10 at 02:49
-
3"Don't ask" means "don't ask me, 'did you check the documentation, what did it say?'" – Ned Batchelder Jun 26 '10 at 02:51
-
-
`[s in os.listdir() if s.endswith('.f')]` results in a syntax error here using Python 2.7. `[s for s in os.listdir('.') if s.endswith('.f')]` works – Enno Gröper Feb 08 '13 at 16:00
-
Just wondering, what is "s" supposed to be here? I tried the code for myself and it works but I find it difficult to understand when seemingly arbitrary variable names are used. – q-compute Aug 16 '19 at 13:04
-
@q-compute It's just a variable which gets set to the name of each file in the directory in turn. The name is arbitrary so you can write it out for yourself with a different variable name if that makes it easier for you to understand. – David Z Aug 16 '19 at 17:46
2
There is another possibility not mentioned so far:
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.f'):
print file
Actually this is how the glob
module is implemented, so in this case glob
is simpler and better, but the fnmatch
module can be handy in other situations, e.g. when doing a tree traversal using os.walk
.

Philipp
- 48,066
- 12
- 84
- 109
1
Try this:
from os import listdir
extension = '.wantedExtension'
mypath = r'my\path'
filesWithExtension = [ f for f in listdir(mypath) if f[(len(f) - len(extension)):len(f)].find(extension)>=0 ]

lev
- 2,877
- 23
- 22
0