python - Why can't I call read() twice on an open file? -
for exercise i'm doing, i'm trying read contents of given file twice using read()
method. strangely, when call second time, doesn't seem return file content string?
here's code
f = f.open() # year match = re.search(r'popularity in (\d+)', f.read()) if match: print match.group(1) # names matches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', f.read()) if matches: # matches none
of course know not efficient or best way, not point here. point is, why can't call read()
twice? have reset file handle? or close / reopen file in order that?
calling read()
reads through entire file , leaves read cursor @ end of file (with nothing more read). if looking read number of lines @ time use readline()
, readlines()
or iterate through lines for line in handle:
.
to answer question directly, once file has been read, read()
can use seek(0)
return read cursor start of file (docs here). if know file isn't going large, can save read()
output variable, using in findall expressions.
ps. dont forget close file after done ;)
Comments
Post a Comment