使用endswith读取文件列表在列表中找不到扩展名 [英] Using endswith to read list of files doesn't find extension in list
问题描述
我试图让我的 python 脚本读取带有扩展名的文件名列表的文本文件,并在找到特定扩展名(确切地说是 .txt 文件)时打印出来.它读取文件并遍历每一行(我已经通过在 for 语句之后放置一个简单的打印行"进行了测试),但是当它在该行中看到.txt"时不执行任何操作.为了避免这个明显的问题,是的,我肯定列表中有 .txt 文件.有人能指出我正确的方向吗?
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)
推荐答案
每行以换行符 '\n'
结束,这样测试就会正确地失败.所以你应该先strip
该行然后测试:
Each line ends with a new line character '\n'
so the test will rightly fail. So you should strip
the line first then test:
line.rstrip().endswith('.txt')
# ^
这篇关于使用endswith读取文件列表在列表中找不到扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!