How do I avoid for loop repetition for action on the same file?


Python noob in the house (yet):

I am handling a file line by line like:

import os

with open ('data.txt','r') as f:
    for line in f:
        os.system("/bin/chmod -x {}".format(line))
        os.system("/usr/bin/clipass {}".format(line))

The main problem is that chmod can fail if the file was not found, and then, for me,the remaining second command is waste of time.

What is the best practice to divide the action in two (besides repeating the loop twice). So I could run chmod on the given list and then make the second iteration to perform the shell script command.


Answer

Preamble:

Now, you could use continue to skip the current item if return code of the command isn't 0 (except for the last command, where it doesn't matter):

with open ('data.txt','r') as f:
    for line in f:
        if subprocess.call(["/bin/chmod","-x",line.rstrip()])
           continue
        subprocess.call(["/usr/bin/clipass",line.rstrip()])