Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use wildcard with os.path.isfile()

People also ask

What does OS path Isfile do?

path. isfile() method in Python is used to check whether the specified path is an existing regular file or not.

What is wildcard file path?

When using wildcards in paths for file collections: * is a simple, non-recursive wildcard representing zero or more characters which you can use for paths and file names. ** is a recursive wildcard which can only be used with paths, not file names. Multiple recursive expressions within the path are not supported.

How does OS path Isdir work?

isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows symbolic link, that means if the specified path is a symbolic link pointing to a directory then the method will return True.

Does OS path join return a string?

os. path. join returns a string; calling the join method of that calls the regular string join method, which is entirely unrelated.


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 fnmatch
import os

def 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"]

Wildcards are expanded by shell and hence you can not use it with os.path.isfile()

If you want to use wildcards, you could use popen with shell = True or os.system()

>>> import os
>>> os.system('ls')
aliases.sh          
default_bashprofile     networkhelpers          projecthelper.old           pythonhelpers           virtualenvwrapper_bashrc
0
>>> os.system('ls *.old')
projecthelper.old
0

You could get the same effect with glob module too.

>>> import glob
>>> glob.glob('*.old')
['projecthelper.old']
>>> 

If you just care about whether at least one file exists and you don't want a list of the files:

import glob
import os

def check_for_files(filepath):
    for filepath_object in glob.glob(filepath):
        if os.path.isfile(filepath_object):
            return True

    return False