Risks of keeping file open forever
<p>I am writing an application that requires reading the next line from a 1GB file exact every 5 minutes; when the end is reached it should start from the top</p>

<p>I had 2 solutions in mind but I'm unsure which one is the best</p>

<p><strong>Solution 1</strong></p>

<pre><code>class I:
    def __init__(self):
        self.count = 0

    def lineFromFile(self) -&gt; str:
        with open('file.txt') as file:
            for i in range(self.count):
                file.readline()
            line = file.readline()
            if not line:
                file.seek(0)
                self.count = 0
            line = file.readline()
            self.count += 1
        return line
</code></pre>

<p><strong>Solution 2</strong></p>

<pre><code>class I:
    def __init__(self):
        self.file = open('file.txt')

    def lineFromFile(self) -&gt; str:
        line = self.file.readline()
        if not line:
            self.file.seek(0)
            line = self.file.readline()
        return line
</code></pre>

<p>Use Solution 1, but don't read line-by-line every time you open the file. Save the last offset read, and <code>seek</code> there directly. Also, you only want to call <code>file.readline()</code> a second time if the first call returned the empty string.</p>

<pre><code>class I:
    def __init__(self):
        self.count = 0
        self.offset = 0

    def lineFromFile(self) -&gt; str:
        with open('file.txt') as file:
            file.seek(self.offset)
            line = file.readline()
            if not line:
                file.seek(0)
                self.count = 0
            else:
                line = file.readline()
            self.count += 1
            self.offset = file.tell()
        return line
</code></pre>

python memory io