DirtyDaver DirtyDaver - 1 year ago 70
Python Question

finding new line characters in a text file

So I have an assignment that involves creating a tail to find the last K 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 "\n" characters within a file. I am running into a few problems. In python my code spits back 6 and in python3 its a 0. The text file has WAY more than this though. Can someone please tell me why this isn't working as I would like?

def new():
f = open("test.txt", "r")
count = 0
for i in f:
if i == "\n":
count = count + 1
return count
print("No file")

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.

edit: code was off.

Answer Source

for i in f: isn't doing what you think it is. The default iterator for a file gives you lines, not characters. So you're saying "Does the entire line equal just a return?"

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

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

If you want to iterate through the individual characters, I would do:

for line in file:
    for char in line:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download