为什么我不能在打开的文件上调用read()两次?

129 投票
7 回答
95472 浏览
提问于 2025-04-16 05:19

在我做的一个练习中,我想用 read() 方法读取一个文件的内容两次。奇怪的是,当我第二次调用它时,似乎没有返回文件内容作为字符串?

这是我的代码

f = f.open()

# get the year
match = re.search(r'Popularity in (\d+)', f.read())

if match:
  print match.group(1)

# get all the names
matches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', f.read())

if matches:
  # matches is always None

当然,我知道这不是最有效或最好的方法,这里不是讨论这个。关键是,为什么我不能调用 read() 两次?我需要重置文件指针吗?还是需要关闭再重新打开文件才能做到这一点?

7 个回答

22

到目前为止,所有回答这个问题的人都是对的——read()这个函数会逐步读取文件的内容,所以一旦你调用了它,就不能再调用一次了。

我想补充的是,在你的具体情况下,你不需要回到文件的开头或者重新打开文件。你可以把读取到的文本存储在一个本地变量里,然后在你的程序中使用它两次,或者想用多少次都可以:

f = f.open()
text = f.read() # read the file into a local variable
# get the year
match = re.search(r'Popularity in (\d+)', text)
if match:
  print match.group(1)
# get all the names
matches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', text)
if matches:
  # matches will now not always be None
52

正如其他回答所提到的,你应该使用 seek() 这个函数。

我来给你写个例子:

>>> a = open('file.txt')
>>> a.read()
#output
>>> a.seek(0)
>>> a.read()
#same output
198

调用 read() 方法会把整个文件的内容都读出来,并把读取的光标放在文件的最后面(这时就没有更多的内容可以读了)。如果你想一次读取特定数量的行,可以使用 readline()readlines(),或者用 for line in handle: 来逐行读取。

直接回答你的问题,一旦文件被读取后,使用 read() 方法后,你可以用 seek(0) 把读取光标移回文件的开头(相关文档可以在 这里 找到)。如果你知道文件不会太大,你也可以把 read() 的结果保存到一个变量里,然后在你的 findall 表达式中使用。

另外,记得在使用完文件后要把它关闭哦。

撰写回答