pythonfile-readcharactercount

Why does this function to count characters in a file always return 0?


I have been trying to define a function that gets 2 inputs (a character and a file path) and returns the amount of times the character appears in it. I know there is a shorter way to do this with the method.count but I would like to know why this function always returns 0.

def lettercount(character , path):
    with open("bear.txt") as myfile:
        counter = [obj for obj in myfile if obj==character]
        return len(counter)

Solution

  • When you iterate over a file (myfile), you get lines (obj). So obj==character will only ever be true if the last line of a file is character and there's no trailing newline.


    To iterate over characters, you can add another loop to your comprehension:

    c for line in myfile for c in line if c==character
    

    Although, you don't actually need to keep the characters themselves since you only need their count. You can use sum() like this:

    count = sum(c==character for line in myfile for c in line)
    return count