How can I execute/run IF statement inside another IF only once? I am reading file, line by line I would like to execute commands inside IF statement only once.
I had tried global variables, define and call Function, but no luck.
Could you please help me?
Example:
i = 0
for x in enumerate(FILE, 1):
i = 1
if re.findall("*test1*", line):
command1
command2
command3
executed = True; (...and do not run commands again when the IF statement is fullfiled with another line from FILE)
CodePudding user response:
Simply add a iteration requirement to the if statement like so:
i = 0
j=0
for x in enumerate(FILE, 1):
i = 1
if j == 0 and re.findall("*test1*", line):
j =1
command1
command2
command3
This means it will only work on the first execution.
You could instead use the "executed" variable if you would like:
i = 0
executed = False
for x in enumerate(FILE, 1):
i = 1
if executed == False and re.findall("*test1*", line):
command1
command2
command3
executed = True
Lastly, if you want to exit the loop entirely after the first execution you can use break like so:
i = 0
for x in enumerate(FILE, 1):
i = 1
if re.findall("*test1*", line):
command1
command2
command3
break
Depends if you need to continue the loop or not.
CodePudding user response:
What you can do is to test not executed before to run the test, then if executed is true, the regex will not be run.
Example :
executed = False
i = 0
for x in enumerate(FILE, 1):
i = 1
if ((not executed) and re.findall("*test1*", line)):
# ... commands
executed = True;
#don't run commands again when the IF statement sees executed is True
Another option would be to just skip the rest of the lines if you just want to ignore them. Example :
i = 0
for x in enumerate(FILE, 1):
i = 1
if (re.findall("*test1*", line)):
# ... commands
executed = True
break # the break will exit the for loop
If that doesn't answer your question, please let me know in the comment. Because it seems to fit the description of your problem, and it works.
