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

Question:

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)
Asked By: DarkKnight4251

||

Answers:

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')
#      ^
Answered By: Moses Koledoye

Use str.rstrip to remove trailing whitespaces, such as n or rn.

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

I guess you should add the endline sign n at the end of the extension:

with open ("file_list.txt", "r") as L:
    for line in L:
        if line.endswith(".txtn"):
            print ("This has a .txt: " + line)
Answered By: Ohad Eytan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.