Search code examples
pythonreadfile

Using endswith to read list of files doesn't find extension in list


I am trying to get my python script to read a text file with a list of file names with extensions and print out when it finds a particular extension (.txt files to be exact). It reads the file and goes through each line (I've tested by putting a simple "print line" after the for statement), but doesn't do anything when it sees ".txt" in the line. To avoid the obvious question, yes I'm positive there are .txt files in the list. Can someone point me in the right direction?

with open ("file_list.txt", "r") as L:
    for line in L:
        if line.endswith(".txt"):
            print ("This has a .txt: " + line)

Solution

  • Each line ends with a new line character '\n', so the test will fail. First use str.strip or str.rstrip on the line, then test:

    line.rstrip().endswith('.txt')
    #      ^