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

前端 未结 3 725
我在风中等你
我在风中等你 2021-01-21 09:11

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

相关标签:
3条回答
  • 2021-01-21 09:36

    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)
    
    0 讨论(0)
  • 2021-01-21 09:44

    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)
    
    0 讨论(0)
  • 2021-01-21 09:48

    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')
    #      ^
    
    0 讨论(0)
提交回复
热议问题