gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:11:14 25 4
gpt4 key购买 nike

对于我正在进行的练习,我尝试使用 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() 两次?我必须重置文件句柄吗?或者关闭/重新打开文件以执行此操作?

最佳答案

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

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

附言。完成后不要忘记关闭文件。

关于python - 为什么我不能在打开的文件上调用 read() 两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3906137/

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