Skip to main content
 首页 » 编程设计

python之如何在python中多次遍历文件

2025年05月04日24zhenyulu

当我执行 while 循环时,我希望我的代码多次遍历同一个文件:

file = open('anyfile.txt', 'r') 
x = 0  
while x<5: 
    for line in file: 
        #does stuff 
    x = x + 1 

我的代码不同,所以我给出了一段更简单的代码作为例子。每当我这样做时,while 循环就会执行,遍历文件一次,然后遍历 while 循环直到它停止,只遍历文件一次。 如何让我的代码多次运行文件?这样做的原因是因为在我的实际代码中,我在每个循环中编辑他的文本文件。请问有人可以帮忙吗?

请您参考如下方法:

您只能迭代迭代器 file 一次,然后它不会再产生了。您可以使用 with open(filename) 每次运行 while 循环时读取文件

while x < 5: 
    with open('anyfile.txt') as inputs: 
        for line in inputs: 
            # do you work here 
    x = x +1