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 in 'text.txt' if w.endswith('os')]
does not give what I want when I call it. On the other hand, if I try naming the open file
f=open('text.txt')
h=[w for w in f if w.endswith('os')]
does not work either. Should I convert the text into a list first?
Comment: I hope this is not duplicate. It is not the same as this former question although close to it.
(w for w in f)
of the file will have a hidden newline character such as'\n'
. So, none of the strings end with os. because they may end with'os\n'
or something of that sort. While I've told you what's happened here, i highly recommend just looking at the variables, say withh = [w for w in f]
and then just watchh[0]
and see the actual line in memory.