Some file read (e.g. readlines()
) functions in Python copy the file contents to memory (as a list).
I need to process a file that's too large to be copied in memory and as such need to use a file pointer (to access the file one byte at a time) -- as in C getc()
.
The additional requirement I have is that I'd like to rewind the file pointer to previous bytes like in C ungetc()
.
Is there a way to do this in Python?
Also, in Python, I can read one line at a time with readline()
.
Is there a way to read the previous line going backward?
If you do want to use a file pointer directly (I think Mike Graham's suggestion is better though), you can use the file object's seek() method which lets you set the internal pointer, combined with the read() method, which support an option argument specifying how many bytes you'd like to read.