Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 319
UwUly Avatar asked Dec 10 '22 23:12

UwUly


2 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
like image 166
chepner Avatar answered May 20 '23 19:05

chepner


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)
like image 26
Honn Avatar answered May 20 '23 18:05

Honn