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

跟風遠走 提交于 2019-12-20 01:58:50

问题


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)

回答1:


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')
#      ^



回答2:


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(".txt\n"):
        print ("This has a .txt: " + line)



回答3:


Use str.rstrip to remove trailing whitespaces, such as \n or \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)


来源:https://stackoverflow.com/questions/38529036/using-endswith-to-read-list-of-files-doesnt-find-extension-in-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!