lundi 24 février 2020

python syntax error for : at end of for if statment, no idea why

I am running the following code:

with open("tmp/"+filename.stem+".txt", "r") as infile:
        readfile = infile.readlines()
        with open("test/"+filename.stem+".txt", "w") as outfile:
            for i, line in enumerate(readfile) if 'M32' in line:
                if '%' in readfile[i - 1]:
                    outfile.write(readfile[i - 6] + '\n')
                    outfile.write(readfile[i - 3] + '\n')
                    outfile.write(readfile[i - 1] + '\n')
                    print(i)
                    print(line)
                else:
                    outfile.write(readfile[i - 3] + '\n')

and getting this error:

 for i, line in enumerate(readfile) if 'M32' in line:
                                                       ^
SyntaxError: invalid syntax

I am not sure why, as far as i am awear the : is correctly placeed. Any idea why this is happening?

Edit: I now know you can't put a conditional inline with a forloop

Aucun commentaire:

Enregistrer un commentaire