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>Why not simplify the logic and use a Python built-in?</p>

<pre><code>def new(): # not a good function name!
    try:
        with open('data1.txt') as f:
            return f.read().count('\n')
    except FileNotFoundError:
        print ("No file")
</code></pre>

python file newline