简体   繁体   中英

check whether some folder presented in path

I am iterating of folders and read files line by line in order to find some substring.

The problem is that I want to ignore some folders during search (like bin or build ).

I tried to add check - but it still include it in the search

def step(ext, dirname, names):
    for name in names:
        if name.lower().endswith(".xml") or name.lower().endswith(".properties") or name.lower().endswith(".java"):
            path = os.path.join(dirname, name)
            if not "\bin\"" in path and not "\build" in path:
                with open(path, "r") as lines:
                    print "File: {}".format(path)
                    i = 0
                    for line in lines:
                        m = re.search(r"\{[^:]*:[^\}]*\}", line)
                        with open("search-result.txt", "a") as output:
                            if m is not None:
                                output.write("Path: {0}; \n    Line number: {1}; \n        String: {2}\n".format(path, i, m.group()))
                        i+=1

I suspect your condition is failing because \\b is being interpreted as the backspace character, rather than a backslash character followed by a "b" character. Also, it looks like you're escaping a quote mark at the end of bin; is that intentional?

Try escaping the backslashes.

if not "\\bin\\" in path and not "\\build" in path:

Kevins answer will do the job, but I prefer to let os.path.split() do this job (so if anyone ever uses the function on different platform it will work):

import os.path

def path_contains(path, folder):
    while path:
        path, fld = os.path.split(path)
        # Nothing in folder anymore? Check beginning and quit
        if not fld:
            if path == folder:
                return True
            return False

        if fld == folder:
            return True

    return False


>>> path_contains(r'C:\Windows\system32\calc.exe', 'system32')
True
>>> path_contains(r'C:\Windows\system32\calc.exe', 'windows')
False
>>> path_contains(r'C:\Windows\system32\calc.exe', 'Windows')
True
>>> path_contains(r'C:\Windows\system32\calc.exe', 'C:\\')
True
>>> path_contains(r'C:\Windows\system32\calc.exe', 'C:')
False
>>> path_contains(r'C:\Windows\system32\calc.exe', 'test')
False

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