作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是编程新手,正在玩弄 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/
我是一名优秀的程序员,十分优秀!