為什么不能在打開的文件上調(diào)用read()兩次?對于我正在做的練習(xí),我嘗試使用read()方法。奇怪的是,當(dāng)我第二次調(diào)用它時,它似乎沒有將文件內(nèi)容作為字符串返回?這是密碼f = f.open()# get the yearmatch = re.search(r'Popularity in (\d+)', f.read())if match:
print match.group(1)# get all the namesmatches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', f.read())if matches:
# matches is always None當(dāng)然,我知道這不是最有效或最好的方法,這不是重點(diǎn)。關(guān)鍵是為什么我不能打電話read()兩次?我必須重置文件句柄嗎?還是關(guān)閉/重新打開文件以完成此操作?
3 回答

暮色呼如
TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個贊
read()
readline()
, readlines()
for line in handle:
.
read()
seek(0)
read()

元芳怎么了
TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個贊
>>> a = open('file.txt')>>> a.read()#output>>> a.seek(0)>>> a.read()#same output
添加回答
舉報
0/150
提交
取消