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?
f = open("test.txt", "r")
count = 0
for i in f:
if i == "\n":
count = count + 1
for i in f: isn't doing what you think it is. The default iterator for a file gives you
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: dostuff()
Naming the variables what you think they are will also help to troubleshoot if they end up not being what you thought.