Continue reading file from the position where it was left

前端 未结 2 548
遥遥无期
遥遥无期 2020-12-19 17:27

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

相关标签:
2条回答
  • 2020-12-19 18:16

    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'
    
    0 讨论(0)
  • 2020-12-19 18:27

    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

    0 讨论(0)
提交回复
热议问题