finding new line characters in a text file
<p>I have an assignment that involves creating a tail to find the last <code>K</code> lines in a file. We have been given a buffer to use for this. For now, I'm trying to write small things and search for <code>"\n"</code> characters within a file. I am running into a few problems. In <code>python</code> my code spits back <strong>6</strong> and in <code>python3</code> its a <strong>0</strong>.  The text file has WAY more than this though. Can someone please tell me why this isn't working as I would like? </p>

<pre><code>def new():
    try:
        f = open("test.txt", "r")
        count = 0
        for i in f:
            if i == "\n":
                count = count + 1
        return count
        f.close()
    except(FileNotFoundError):
        print("No file")      
</code></pre>

<p>What I would like to do is use seek to go backwards in the file and every so often search for the new line characters but this doesn't even seem to work for me. </p>

<p>A much simpler approach would be to</p>

<ul>
<li>use Python's built-in ability to split a file into a list of lines</li>
<li>create your tail from the last K elements of that list</li>
</ul>

<p>If keeping the whole file in an array is a problem, you could instead read the file line-by-line, but only retain the last K lines read, so that when you reach the end of the file, you have the tail you want.</p>

python file newline