使用 endswith 读取文件列表未在列表中找到扩展名

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

我正在尝试让我的 python 脚本读取一个包含文件名列表和扩展名的文本文件,并在找到特定扩展名(确切地说是 .txt 文件)时打印出来。它读取文件并遍历每一行(我通过在 for 语句后放置一个简单的 "print line" 进行了测试),但是当它在该行中看到“.txt”时不执行任何操作。为避免明显的问题,是的,我肯定列表中有 .txt 文件。有人能指出我正确的方向吗?

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

每行以换行符结束 '\n' 因此测试将正确地失败。所以你应该先 strip 该行然后测试:

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

使用str.rstrip删除尾随空格,例如\n\r\n

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

我猜你应该在扩展末尾添加结束符 \n:

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