Print values from list based from separate text file
<p>How do I print a list of words from a separate text file? I want to print all the words unless the word has a length of 4 characters.  </p>

<p>words.txt file looks like this:</p>

<p>abate  chicanery   disseminate gainsay latent  aberrant    coagulate   dissolution garrulous   laud</p>

<p>It has 334 total words in it. I'm trying to display the list until it reaches a word with a length of 4 and stops. </p>

<pre><code>wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()

#List outputs length of words in list

lengths= [len(i) for i in wordList]
for i in range(10):
    if i &gt;= len(lengths):
         break
    print(lengths[i], end = ' ')

# While loop displays names based on length of words in list

while words != 4:
    if words in wordList:
        print("\nSelected words are:", words)
    break
</code></pre>

<h1>output</h1>

<pre><code>5 9 11 7 6 8 9 11 9 4
</code></pre>

<h1>sample desired output</h1>

<p>Selected words are:</p>

<p>Abate </p>

<p>Chicanery </p>

<p>disseminate </p>

<p>gainsay </p>

<p>latent  </p>

<p>aberrant    </p>

<p>coagulate   </p>

<p>dissolution </p>

<p>garrulous   </p>

<p>Given that you only want the first 10 words. There isn't much point reading all 4 lines. You can safely read just the 1st and save yourself some time.</p>

<pre><code>#from itertools import chain

with open('words.txt') as f:

    # could raise `StopIteration` if file is empty
    words = next(f).strip().split()

    # to read all lines
    #words = []
    #for line in f:
    #    words.extend(line.strip().split())

    # more functional way
    # words = list(chain.from_iterable(line.strip().split() for line in f))

print("Selected words are:")
for word in words[:10]:
    if len(word) != 4:
        print(word)
</code></pre>

<p>There are a few alternative methods I left in there but commented out. </p>

<p>Edit using a while loop. </p>

<pre><code>i = 0
while i &lt; 10:
    if len(words[i]) != 4:
        print(words[i])
    i += 1
</code></pre>

<p>Since you know how many iterations you can do, you can hide the mechanics of the iteration using a <code>for</code> loop. A while does not facilitate this very well and is better used when you don't know how many iterations you will do.</p>

python python-3.x