Search code examples
pythonreadlinereadlines

How to use a number in the first line of a .txt file to determine the number of words to be printed?


I have this:

from random_word import RandomWords
import time

h = open('/home/rodrigo/Documents/num.txt', 'r')
content = h.readline()

print (content)


a = 0
for line in content:
    for i in line:
        if i.isdigit() == True:
            a += int(i)

r = RandomWords()
key = r.get_random_words()
time.sleep(3)
keys = key[:a]
time.sleep(1)
for key in keys:
    print(key)

I'm trying to read and use the number on the first line of a .txt file. In the .txt file I have just typed the number:

50

However, this code reads only the first digit of the number fifty and the result is that the function print(key) prints only 5 words (it should print 50 words).

If I change the .txt file to the number: 55 The print(key) prints 10 words and not 55 words. (the function is adding the digits/numeric units of the .txt file)

Can anybody help? How to print an amount of words exactly equal to the number typed in the .txt file?


Solution

  • It reads both digits. But it reads it to a string "50". You then iterate over the digits, convert them to ints and add them up, i.e. int("5") + int("0"). Which gives you 5 (obviously).

    So just replace your whole loop with

    a = int(content)
    

    if you want to check that file only has digits:

    try:
        a = int(content)
    except ValueError:
        print("The content is not intiger")