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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With