为什么我不能在打开的文件上调用read()两次? [英] Why can't I call read() twice on an open file?

查看:330
本文介绍了为什么我不能在打开的文件上调用read()两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在进行的练习,我试图使用 read()方法两次读取给定文件的内容。奇怪的是,当我第二次调用它时,它似乎没有将文件内容作为字符串返回?

For an exercise I'm doing, I'm trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?

这是代码

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()?我是否必须重置文件句柄?或者关闭/重新打开文件以进行此操作?

Of course I know that this is not the most efficient or best way, this is not the point here. The point is, why can't I call read() twice? Do I have to reset the file handle? Or close / reopen the file in order to do that?

推荐答案

调用 read()读取整个文件并将读取光标留在文件的末尾(没有更多内容可读)。如果您希望一次读取一定数量的行,可以使用 readline() readlines()或者使用遍历句柄中的行:

Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.

直接回答您的问题,一旦文件被记录读取,使用 read()您可以使用 seek(0)将读取光标返回到文件的开头(文档是此处)。如果您知道文件不会太大,您还可以将 read()输出保存到变量中,并在findall表达式中使用它。

To answer your question directly, once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). If you know the file isn't going to be too large, you can also save the read() output to a variable, using it in your findall expressions.

Ps。完成后不要忘记关闭文件;)

Ps. Dont forget to close the file after you are done with it ;)

这篇关于为什么我不能在打开的文件上调用read()两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆