Skip to content Skip to sidebar Skip to footer

Python If == True Statement Only Working On Last Line Of Readline

My function only says that the last word in a file of words is an anagram (the first helper function). But every word in the file is an anagram of the word I tested and returns tru

Solution 1:

This is expected, based on the method you use to read a line (file.readline). From the documentation:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

Your line has a trailing newline, but word certainly does not. So, in the end, all you'd need to change is:

line = content.readline().rstrip()

Well, that's all you'd need to change to get it working. Additionally, I'd also recommend using the with...as context manager to handle file I/O. It's good practice, and you'll thank yourself for it.

with open("small_list.txt") as f:
    for line in f:
        if is_anagram(word, line.rstrip()):
            ... # do something here

It's better to use a for loop to iterate over the lines of a file (rather than a while, it's cleaner). Also, there's no need to explicitly call f.close() when you use a context manager (you're not currently doing it, you're only referencing the method without actually calling it).


Incorporating @Christian Dean's suggestion in this answer, you can simplify your anagram function as well - call sorted and return the result in a single line:

def is_anagram(a, b):
    return sorted(a) == sorted(b)

Post a Comment for "Python If == True Statement Only Working On Last Line Of Readline"