Cyker
Cyker

Reputation: 10994

Python - Why does fnmatch match files in subdirs?

Why does this return True:

fnmatch('/home/user/a/b', '/home/user/*')

while ls -d /home/user/* doesn't give /home/user/a/b at all.

Upvotes: 0

Views: 79

Answers (1)

KromviellBlack
KromviellBlack

Reputation: 918

fnmatch сhecks only names (strings) - without verification of the existence of real files.

To check file existence you may use os.path.exists(path) call. Like this:

from fnmatch import fnmatch
from os.path import exists

pattern = '/home/user/*'
name = '/home/user/a/b'

if exists(name):
    if fnmatch(name, pattern):
        print('"{}" exists and matches'.format(name))

Upvotes: 2

Related Questions