Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...