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><code>for i in f:</code> isn't doing what you think it is. The default iterator for a file gives you <code>lines</code>, not <code>characters</code>. So you're saying "Does the entire line equal just a return?"</p>

<p>Try instead doing <code>if i[-1] == "\n":</code> as this says "Is the last character in the line a newline?"</p>

<p>You might notice that this is trivially true, as each "line" is ended by a newline, so simply counting the lines is sufficient.</p>

<hr>

<p>If you want to iterate through the individual characters, I would do:</p>

<pre><code>for line in file:
    for char in line:
        dostuff()
</code></pre>

<p>Naming the variables what you think they are will also help to troubleshoot if they end up not being what you thought.</p>

<hr>

<p>Example on <a href="https://repl.it/Dzaf/0" rel="nofollow">repl.it</a>. The variables are named <code>line</code> and <code>char</code> just to show what they are, they could be <code>banana</code> and <code>henry</code> just as easily, although then it would be less clear what was happening. <code>raven</code> simulates a file for the purposes of this example.</p>

python file newline