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>Generally, the biggest risk of <em>lazily</em> reading from a file is another process writing to the file while you're reading from it.</p>

<p>Do the contents of the file change?  Is the file massive?  If not, just read the whole file at startup.</p>

<p>Does the file change a lot? Are lots of other processes writing to it? Can other processes delete lines?  If that's the case, you should probably just store your <code>seek</code>/line number position and then reopen and close the file every 5 minutes, check if you're at the end of file and keep reading. In this case you should also use some type of <em>lock file</em> or other synchronization mechanism to prevent multiple processes from trying to read and write from the same file at the same time.</p>

python memory io