Use wildcard with os.path.isfile() Use wildcard with os.path.isfile() python python

Use wildcard with os.path.isfile()


glob is what you need.

>>> import glob>>> glob.glob('*.rar')   # all rar files within the directory, in this case the current working one

os.path.isfile() returns True if a path is an existing regular file. So that is used for checking whether a file already exists and doesn't support wildcards. glob does.


Without using os.path.isfile() you won't know whether the results returned by glob() are files or subdirectories, so try something like this instead:

import fnmatchimport osdef find_files(base, pattern):    '''Return list of files matching pattern in base folder.'''    return [n for n in fnmatch.filter(os.listdir(base), pattern) if        os.path.isfile(os.path.join(base, n))]rar_files = find_files('somedir', '*.rar')

You could also just filter the results returned by glob() if you like, and that has the advantage of doing a few extra things relating to unicode and the like. Check the source in glob.py if it matters.

[n for n in glob(pattern) if os.path.isfile(n)]


import os[x for x in os.listdir("your_directory") if len(x) >= 4 and  x[-4:] == ".rar"]