Lazy Method for Reading Big File in Python?

To write a lazy function, just use yield: def read_in_chunks(file_object, chunk_size=1024): “””Lazy function (generator) to read a file piece by piece. Default chunk size: 1k.””” while True: data = file_object.read(chunk_size) if not data: break yield data with open(‘really_big_file.dat’) as f: for piece in read_in_chunks(f): process_data(piece) Another option would be to use iter and a helper … Read more

Understanding generators in Python

Note: this post assumes Python 3.x syntax.† A generator is simply a function which returns an object on which you can call next, such that for every call it returns some value, until it raises a StopIteration exception, signaling that all values have been generated. Such an object is called an iterator. Normal functions return … Read more