I am searching in files with extensions .xml.xml, .java.java, and .properties.properties strings that match a certain regular expression.
When I find it -, I write it to the file with the filename, line and string information.
My code looks like this
def search(param):
filename = "search-result.txt"
try:
os.remove(filename)
except OSError:
pass
os.path.walk(param, step, None)
def step(ext, dirname, names):
output = open("search-result.txt", "a")
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)
filters = ["\\bin\\", "\\build\\", "logback", "\\test\\", "\\target\\"]
if all(not filter in path for filter in filters):
with open(path, "r") as lines:
print "Read: {}".format(path)
i = 1
for line in lines:
m = re.search(r"(!|$|RUP)\{[^:]*:[^\}]*\}", line)
if m is not None:
output.write("Path: {0}; \n Line number: {1}; \n {2}\n".format(path, i, line))
i += 1
output.close()
I divided it into two functions - function search, where I can check where result file is existed and remove it, and then step function for os.path.walk. Param - is a folder to search in.
How can be this code be adjusted to look better?