Search code examples
python-3.xmethodsreadline

How does Python keep track of where it is in a file when using .readline()


Python keeps track of which line has been read using readline, how does it do this.

fin = open('/etc/passwd')
fin.readline()

When I run readline again it reads the second line.


Solution

  • Quite simply by keeping track of the file pointer's current position. Here's a very very very dumbed down example (the real implementation is based on system level representation of file objects, handles buffering etc etc, well it's more complex by one or more orders of magnitude - but the underlying principle is just the same).

    class FakeFile(object):
        def __init__(self, text):
            self.text = text
            self.length = len(text)
            self.pointer = 0
    
        def readline(self):
            if self.pointer >= self.length:
                # we've already read all the content
                return ""
    
            buffer = []
            while self.pointer < self.length:
                buffer.append(self.text[self.pointer])
                self.pointer += 1
                if buffer[-1] == "\n":
                    break
            return "".join(buffer)
    
    
        def seek(self, position):
            if position < 0 or position > self.length:
                raise IOError("Invalid argument", 22)
    
            self.pointer = position
    
        def tell(self):
            return self.position
    
        # etc