对于我正在进行的练习,我正在尝试使用该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()两次打电话?我是否必须重置文件句柄?或者关闭/重新打开文件以执行此操作?
Tim*_*Tim 135
调用read()读取整个文件并将读取光标留在文件的末尾(没有更多内容可读).如果您希望一次读取一定数量的行readline(),readlines()或者使用 行迭代for line in handle:.
要直接回答您的问题,一旦读取了文件,read()您就可以使用seek(0)将读取光标返回到文件的开头(文档在这里).如果您知道文件不会太大,您还可以将read()输出保存到变量中,并在findall表达式中使用它.
PS.完成之后别忘了关闭文件;)
Ant*_*Ant 24
是的,如上所述......
我只写一个例子:
>>> a = open('file.txt')
>>> a.read()
#output
>>> a.seek(0)
>>> a.read()
#same output
Run Code Online (Sandbox Code Playgroud)
Tom*_*son 16
到目前为止回答这个问题的每个人都是绝对正确的 - read()在文件中移动,所以在你打电话之后,你再也不能打电话了.
我要补充的是,在您的特定情况下,您不需要寻找开头或重新打开文件,您只需将您在本地变量中读取的文本存储起来,并使用它两次,或者在您的计划中,您可以多次使用:
f = f.open()
text = f.read() # read the file into a local variable
# get the year
match = re.search(r'Popularity in (\d+)', text)
if match:
print match.group(1)
# get all the names
matches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', text)
if matches:
# matches will now not always be None
Run Code Online (Sandbox Code Playgroud)