Undo a file readline() operation so file-pointer is back in original state

You have to remember the position by calling file.tell() before the readline and then calling file.seek() to rewind. Something like: fp = open(‘myfile’) last_pos = fp.tell() line = fp.readline() while line != ”: if line == ‘SPECIAL’: fp.seek(last_pos) other_function(fp) break last_pos = fp.tell() line = fp.readline() I can’t recall if it is safe to call … Read more

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever. I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read(). The documentation for readlines() explicitly guarantees that it … Read more