re.search()在再次调用时返回None [重复] - python

This question already has answers here:

Why can't I call read() twice on an open file?

(7个答案)

5年前关闭。

这是我第一次在python中使用re软件包。

为了更好地理解它,我决定将一首诗复制到我的文件中,并使用不同的正则表达式来玩re.search()。

我从以下网站得到这首诗并将其复制到我的文本文件中:
http://www.poets.org/poetsorg/poem-day

我还提到了this,this,this和this,以帮助解决我的问题。

以下是我的代码:

searchFile = open ('/Users/admin/Documents/Python/NLP/Chapter1-TextSample.txt', 'r')

for line in searchFile:
    if re.search('[pP]igeons', line):
        print line

The pigeons ignore us gently as we
scream at one another in the parking
lot of an upscale grocer. 

Pigeons scoot,and finches hop, and cicadas shout and shed
themselves into loose approximations of what
we might have in a different time called heaven.


for line in searchFile:
    if re.search('[pP]igeons', line):
        print line


for line in searchFile:
    print line

如您所见,当我第一次搜索时,我得到正确的结果。那里没有问题。但是,一旦再次执行相同的搜索,或者即使我只是尝试打印文件的行,也不会显示任何内容。但是,当我检查“ searchFile”对象时,它仍然存在,如下所示:

In[23]:  searchFile
Out[23]: <open file '/Users/admin/Documents/Python/NLP/Chapter1-TextSample.txt', mode 'r' at 0x103a85d20>

有人可以强调为什么会这样吗?我想念什么吗?

python大神给出的解决方案

您已到达文件末尾。您应该能够执行此操作以回到开始:

searchFile.seek(0)