gpt4 book ai didi

python - 如何在 Python 中结束 for 循环?

转载 作者:行者123 更新时间:2023-11-28 20:47:41 24 4
gpt4 key购买 nike

我是编程新手,正在玩弄 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 循环在到达文件末尾时停止?有没有更正确的方法来编写这段代码?

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

最佳答案

>>> f = open("test.txt")
>>> a = f.read()
>>> f.close()
>>> a = a.replace("ape", "\nape")
>>> print(a)

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

关于python - 如何在 Python 中结束 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18337332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com