对于我正在进行的练习,我正在尝试使用该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
Run Code Online (Sandbox Code Playgroud)
当然我知道这不是最有效或最好的方式,这不是重点.关键是,为什么我不能read()两次打电话?我是否必须重置文件句柄?或者关闭/重新打开文件以执行此操作?
我有一个问题要理解迭代文件,在这里我继续我在解释器上输入的内容和结果:
>>> f = open('baby1990.html', 'rU')
>>> for line in f.readlines():
... print(line)
...
# ... all the lines from the file appear here ...
Run Code Online (Sandbox Code Playgroud)
当我再次尝试迭代同一个打开的文件时,我什么也没得到!
>>> for line in f.readlines():
... print(line)
...
>>>
Run Code Online (Sandbox Code Playgroud)
根本没有输出,为了解决这个问题,我要关闭()文件,然后再打开它进行阅读!! 这是正常的行为吗?