Why is my code not showing any output? I am trying to use while loop to debug the error i was getting before it

Viewed 119
f = file.readlines()
l = 0
while l <= len(f):
    for i in range(l):
        x = f[i]
        l += 1
        for a in x:
            if a == "a":
                f.pop(i)
                break
            else:
                continue
print(f)
file.close()

I want to pop any line from the data which has any character 'a' in it.

3 Answers

You don't need to manage your own line counter and iterate over each line character by character. The file itself is iterable without using readlines, and the in operator tells you at once if "a" is a character in a given line.

with open("filename") as f:
    for line in f:
        if "a" in line:
            print(line, end="")  # line already ends with a newline

Im not quite understanding the way your code is supposed to work, but this would solve your problem too:

f = file.readlines()

for line in reversed(f):
    if "a" in line:
        f.remove(line)

for i in range(l) when l is zero will cause the loop to run zero times.

Related