Python - 为什么 fnmatch 匹配子目录中的文件?

Python - Why does fnmatch match files in subdirs?

为什么会这样 return True:

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

ls -d /home/user/* 根本不给 /home/user/a/b

fnmatch сhecks only names (strings) - 不验证真实文件的存在。

要检查文件是否存在,您可以使用 os.path.exists(path) 调用。像这样:

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))