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

编程入门 行业动态 更新时间:2024-10-27 22:19:31
为什么我不能在打开的文件中调用read()两次?(Why can't I call read() twice on an open file?)

对于我正在做的练习,我试图用read()方法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()两次? 我必须重置文件句柄吗? 或者关闭/重新打开文件,以此做到这一点

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?

Here's the code

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

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()或for line in handle:进行迭代for line in handle: 。

要直接回答你的问题,一旦读了一个文件,用read()可以使用seek(0)把读取的光标返回到文件的开头(docs在这里 )。 如果您知道文件不会太大,您还可以将read()输出保存到变量中,并在findall表达式中使用它。

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

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:.

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. Dont forget to close the file after you are done with it ;)

更多推荐

本文发布于:2023-07-27 14:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1291669.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我不   两次   能在   文件   read

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!