2

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 

2 Answers 2

2

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: 
Sign up to request clarification or add additional context in comments.

1 Comment

I am not if OP runs this code on Windows. Probably he should use os.path.sep instead of '\\'
1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.