file - What's perfect counterpart in Python for "while not eof" -


to read text file, in c or pascal, use following snippets read data until eof:

while not eof begin   readline(a);   do_something; end; 

thus, wonder how can simple , fast in python?

loop on file read lines:

with open('somefile') openfileobject:     line in openfileobject:         do_something() 

file objects iterable , yield lines until eof. using file object iterable uses buffer ensure performant reads.

you can same stdin (no need use raw_input():

import sys  line in sys.stdin:     do_something() 

to complete picture, binary reads can done with:

from functools import partial  open('somefile', 'rb') openfileobject:     chunk in iter(partial(openfileobject.read, 1024), ''):         do_something() 

where chunk contain 1024 bytes @ time file.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -