anshul
anshul

Reputation: 119

Continue reading file from the position where it was left

I have to read a file multiple times in which some error info is appended everyday. Is there a way to start reading the file from the point it was left previous day instead of start reading from beginning again? I don't have permission to write in file. so marking the end is out of option. One possible way i got is to store the cursor position and then seek to that position next time.. Is there any other way through python?

Upvotes: 6

Views: 4744

Answers (2)

gabhijit
gabhijit

Reputation: 3585

Yes - it's possible. I believe - you've a file whose size is pretty big enough that you don't want to read from start every time. So here's something you can do - write to a file in your home directory .fileinfo or something and in that write the last offset of the file you read in that file. And then your program can do something like following

if not os.path.exists('/home/.fileinfo'):
     seek_from = 0
else:
     of = open('/home/.fileinfo', 'r')
     seek_from = int(of.readline().strip())

with open('/path/to/your/file', 'r') as f:
    f.seek(seek_from, 0)

    # do whatever you want
    f.seek(0,-1) # Go to the end of the file
    end = f.tell() # Get the position
    of = open('/home/.fileinfo', 'w')
    of.write(str(end))
    of.close()

Something along these lines.

Hope that helps

Upvotes: 4

Eric Appelt
Eric Appelt

Reputation: 2973

You can use the python tell file method to see what position you are in a file before you close it and the seek method to return to that position after you open it again.


Example:

Given a file foo with the contents

edas
agfa
agf
fgfgfg

You can return to a given position as follows:

>>> f = open('foo')
>>> f.tell()
0
>>> f.readline()
'edas\n'
>>> f.tell()
5
>>> f.close()
>>> f = open('foo')
>>> f.tell()
0
>>> f.seek(5)
>>> f.readline()
'agfa\n'

Upvotes: 10

Related Questions