如何在Python中结束for循环?

2024-06-01 05:17:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手,正在玩Python脚本。

我正在尝试编写一个Python脚本,它将读取一个文本文件并打印到屏幕上,搜索一个单词,每次找到这个单词时,都会分割该行的数据。

test.txt文件如下:

ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar

我希望屏幕上的最终结果是:

ape bear cat dog
ape elephant frog giraffe
ape horse iguana jaguar

我的代码:

file = "test.txt"
read_file = open(file, "r")
with read_file as data:
    read_file.read()
    print(data)
    word = "ape"
    for word in data:
        data.split()
        print(data)

我将文件设为变量,因为我打算在脚本中多次使用它。

当我测试代码时,for循环并没有在一个循环之后停止。它最终结束了,但我确信是代码或程序自动结束了无限循环。

如何编辑代码,以便for循环在到达文件末尾时停止? 有没有更正确的方法来写这段代码?

同样,这只是一个示例文件,不是我的实际文件。 谢谢!


Tags: 文件代码testtxt脚本forreaddata