gpt4 book ai didi

python - 在文件中搜索单词后读取文件的剩余行

转载 作者:行者123 更新时间:2023-11-30 23:29:02 25 4
gpt4 key购买 nike

我正在尝试在找到单词后读取文件的其余部分。

我正在尝试编写一个程序来搜索文件中的单词,然后,当找到该单词时,它需要对该单词下方/之后的剩余行执行某些操作。

这是我到目前为止所拥有的,但它不起作用。请协助。谢谢。

def readFile():
with open(“file.txt”, "r") as file:
for line in file:
if “Hello” in line:
break
nextline = file.readlines()
for line in nextline
print(line)

最佳答案

您不能混合迭代(它基本上在循环中调用 file.next 方法)和 readlines

引用一位伟人的话(和 file.next 文档):

In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right

您只需使用迭代就可以做得很好:

def readFile():
with open("file.txt", "r") as file:
for line in file:
if "Hello" in line:
break
for line in file:
# do something with the line

关于python - 在文件中搜索单词后读取文件的剩余行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21354627/

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