我正在进行练习,尝试使用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()
两次?我必须重置文件句柄吗?还是必须关闭/重新打开文件才能这样做?