Python中While循环内For循环仅执行一次的原因及解决办法
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

