Clinton Vlasak Clinton Vlasak - 1 year ago 83
Python Question

Print values from list based from separate text file

I'm trying to use a while loop to parse over a separate text file. I want it to print words from the list I created called lengths[]. This list outputs the length of the first ten words in the text file. I want to display the value of the contents of the list lengths[]. Any suggestions?

words.txt file looks like this:

abate chicanery disseminate gainsay latent aberrant coagulate dissolution garrulous laud

It has 334 total words in it. I'm trying to display the first 10 words excluding the last one which has a length of 4

wordsFile = open("words.txt", 'r')
words =
wordList = words.split()

#List outputs length of words in list

lengths= [len(i) for i in wordList]
for i in range(10):
if i >= len(lengths):
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)


5 9 11 7 6 8 9 11 9 4

sample desired output

Selected words are:










Answer Source

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.

#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:

There are a few alternative methods I left in there but commented out.

Edit using a while loop.

i = 0
while i < 10:
    if len(words[i]) != 4:
        i += 1

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download