Reputation: 183
I have a file which contains:
XYZname_1
XYZname_2
XYZname_3
In my script I am using a re.search to check if the names are incorrect, if they are I do a raise exception
. If both names are incorrect it will only raise exception on the first on and then "crash", in other words the "user" won't know if the second or third name is incorrect.
for my_file in args.cpath:
contents = open(my_file).read()
replaced_contents = my_func(contents,my_file)
def my_func(my_file_contents, filename):
for x in range(0, 3):
#Some code here which is not related to the problem
#In this if-statement I check if it does not match with re.search
#I assume a for-loop should be here? but not sure how to implement it.
if not re.search(r'(.*)XYZname_{0}\(\)\) = .*;(.*)'.format(x+1), my_file_contents):
raise Exception("The name: XYZname_{0} was not found".format(x+1) + " in " + filename)
Lets say the names we saw before are written like this in a file(they are wrong)
XYZnameHE_1
XYZnameGJ_2
XYZnameAsd_3
Then my script should tell me it can't find XYZname_1,2 and 3 in the given file.
Of course there could be other names as well, which another function takes care of. These names could start with XXXname_1,2 3 etc. And if one of them are missing i should get an exception for that one as well
Right now I get this output:
Exception: The name: XYZname_1 was not found in C:\Path
But I would like something like this:
Exception: The name: XYZname_1 was not found in C:\Path
Exception: The name: XYZname_2 was not found in C:\Path
Exception: The name: XYZname_3 was not found in C:\Path
Exception: The name: XXXname_2 was not found in C:\Path
Don't know what the "best practice" is for solving this. One option is to let the script finish looking through the whole file and then "crash"/raise? Or just "crash"/raise directly when it finds an issue? Because it would be annoying for the developer to run the script multiple times in order to find all misisng/wrong names.
Upvotes: 0
Views: 111
Reputation: 986
Use try/catch on each item in your iteration instead of a single pass:
for x in range():
try:
re.search ...
except:
raise exception ...
Not a python expert but from a pure code/logic perspective that should do the trick.
Upvotes: 0
Reputation: 473893
Collect the names/matches in a list. Then, after the loop, raise an exception if necessary. You also need findall()
instead of search()
from what I understand.
At the end you would have something like:
matches = []
for x in range(0, 3):
#Some code here which is not related to the problem
# add the matches to the list
matches.extend(re.findall(r'(?:.*)(XYZname_{0})\(\)\) = .*;(?:.*)'.format(x+1), my_file_contents))
if matches:
for match in matches:
print("The name: {0} was not found in {1}".format(match, filename))
raise Exception(...)
I've also replaced the ()
with (?:)
in your expression - replaced capturing groups with non-capturing. Also added ()
around XYZname_{0}
to capture the name.
Upvotes: 1