python - How come file.readline() works, yet open('name of file', 'r').readline() does not? -
python - How come file.readline() works, yet open('name of file', 'r').readline() does not? -
i have solved dilemma has cost me @ to the lowest degree 3 hours of life:
>>> open('foo.py','r') >>> open('foo.py','r').readline() >>> ''
i tried various combinations, , no avail, , of course of study asked uncle google
this know howewer, work
>>> bar=open('foo.py','r') >>> bar.readline() >>> 'crap' >>> bar.readline() >>> 'more crap' >>> bar.readline() >>> 'even more crap' >>> bar.readline() >>> 'end of crap'
so, thought value assigned variable that. simple seems can't be, otherwise code work either way.
instead of asking direct answer, have materials go over, not wiki page, that's bit advanced, article of sorts.
calling readline()
on file object read file until finds linebreak , homecoming whatever has read. during process, internal pointer positioned on next line, phone call of readline()
read next line, until end of file found.
the internal pointer of course of study kept if maintain referring same file object. calling open()
give such file object, calling open()
1 time again give independent file object.
so doing open(…).readline()
twice open file, read first line, , throw away file object then—twice. sec readline()
phone call refer new file object of course of study not share pointer first one.
so if want read through total file, should utilize one file object , phone call readline()
repeatedly on one.
finally note calling method means adding parentheses @ end. otherwise, refer method without calling it.
python file python-3.x readline
Comments
Post a Comment