简体   繁体   中英

python check folder path with *

checking folder path with "*"

here is what i have tried.

import os

    checkdir = "/lib/modules/*/kernel/drivers/char"
    path = os.path.exists(checkIPMI_dir)
    print path

False

this will always print False, is there other way that i can print it to true? i know when i put static path, it can

import os

    checkdir = "/lib/modules"
    path = os.path.exists(checkIPMI_dir)
    print path

i cant put static, because i have a few linux OS, that uses different kernel version, there for the number will not be the same.

This may not solve your problem, but a while ago I needed to be able to recurse an unknown number of times through a directory structure to find a file, so I wrote this function:

import os
import fnmatch
def get_files(root, patterns='*', depth=1, yield_folders=False):
    """
    Return all of the files matching patterns, in pattern.
    Only search to teh specified depth
    Arguments:
        root - Top level directory for search
        patterns - comma separated list of Unix style
                   wildcards to match NOTE: This is not
                   a regular expression.
        depth - level of subdirectory search, default
                1 level down
        yield_folders - True folder names should be returned
                        default False
    Returns:
        generator of files meeting search criteria for all
        patterns in argument patterns
    """
    # Determine the depth of the root directory
    root_depth = len(root.split(os.sep))
    # Figure out what patterns we are matching
    patterns = patterns.split(';')

    for path, subdirs, files in os.walk(root):
        # Are we including directories in search?
        if yield_folders:
            files.extend(subdirs)
        files.sort()

        for name in files:
            for pattern in patterns:
                # Determine if we've exceeded the depth of the
                # search?
                cur_depth = len(path.split(os.sep))
                if (cur_depth - root_depth) > depth:
                    break

                if fnmatch.fnmatch(name, pattern):
                    yield os.path.join(path, name)
                    break

With this function you could check to see if a file exists with the following:

checkdir = "/lib/modules/*/kernel/drivers/char"
matches = get_files(checkdir, depth=100, yield_folders=True)
found = True if matches else False

All this may be overkill, but it should work!

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