问题
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