对于我正在进行的练习,我正在尝试使用该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)
根本没有输出,为了解决这个问题,我要关闭()文件,然后再打开它进行阅读!! 这是正常的行为吗?
我也试过寻找答案,但我不明白其他人类似问题的答案......
tfile= open("/home/path/to/file",'r')
def temp_sky(lreq, breq):
for line in tfile:
data = line.split()
if ( abs(float(data[0]) - lreq) <= 0.1
and abs(float(data[1]) - breq) <= 0.1):
T= data[2]
return T
print temp_sky(60, 60)
print temp_sky(10, -10)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
7.37052488
Traceback (most recent call last):
File "tsky.py", line 25, in <module>
print temp_sky(10, -10)
File "tsky.py", line 22, in temp_sky
return T
UnboundLocalError: local variable 'T' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
第一个print语句正常工作,但第二个不起作用.我尝试将T设为全局变量,但这使得两个答案都相同!请帮忙!