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
with open('text.txt') as f:
words = [word for line in f for word in line.split() if word.endswith('os')]
Your first attempt does not read the file, or even open it. Instead, it loops over the characters of the string 'text.txt'
and checks each of them if it ends with 'os'
.
Your second attempt iterates over lines of the file, not words -- that's how a for
loop works with a file handle.