Lamma
Lamma

Reputation: 1507

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

Upvotes: 0

Views: 60

Answers (2)

CodeGorilla
CodeGorilla

Reputation: 913

You can't combine a for loop with an if statement...

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')

Upvotes: 1

chepner
chepner

Reputation: 530843

You can't add a filter in this position; it's not a comprehension or generator expression.

for i, line in enumerate(readfile):
    if 'M32' not in line:
        continue
    ...

You can, however, filter the file iterator with a generator expression:

for i, line in enumerate(line for line in readfile if 'M32' in line):

Upvotes: 4

Related Questions