You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中While循环内For循环仅执行一次的原因及解决办法

Why the for loop only runs once

The problem here boils down to how file reading works in Python. When you call file.readlines() for the first time, it reads all lines from the file and moves the file pointer to the very end of the file. After that, every subsequent call to file.readlines() will return an empty list because there’s nothing left to read from the current position of the pointer. That’s why your for loop only executes once—after the first iteration, there’s no data left to loop over.

Fix 1: Reset the file pointer to the start each time

You can use file.seek(0) to move the pointer back to the beginning of the file before calling readlines() again. Here’s how to adjust your code:

start = 0
end = 100
file = open("numbers.txt", "r")
while start <= end:
    file.seek(0)  # Reset pointer to the start of the file
    for x in file.readlines():
        print(x)
    print(start)
    start += 1
file.close()  # Don't forget to close the file when finished!

Fix 2: Read the lines once and store them in a list

A more efficient approach is to read all lines into a list once before the while loop, then iterate over that list each time. This avoids repeatedly reading from the disk, which is faster and cleaner:

start = 0
end = 100
with open("numbers.txt", "r") as file:  # Using 'with' auto-closes the file
    lines = file.readlines()  # Store all lines in a reusable list

while start <= end:
    for x in lines:
        print(x)
    print(start)
    start += 1

Note: Using the with statement is considered best practice because it ensures the file is closed automatically, even if an error occurs during execution.

内容的提问来源于stack exchange,提问作者Mhmoud Amsha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 20:37:57