简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM