I want to separate the exact words of a text file (text.txt) ending in a certain string by using \'endswith\'. The fact is that my variable
h=[w for w i
f=open('text.txt')
h=[w for w in f if w.endswith('os')]
This should work properly. Reasons it may be not working for you,
strip
the line first. There may be hidden ascii chars, like "\n". You can use rstrip()
method for that. Something like this.h=[w.rstrip() for w in f if w.rstrip().endswith('os')]
w
pointer reaches the End Of File (EOF), and hence any more read-operations will be in vain. To move the pointer back to the starting of the file, either use seek
method, or re-open the file.