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

不打扰是莪最后的温柔 提交于 2019-12-01 21:58:34

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

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)

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