Home > front end >  Generate random numbers and write to text file
Generate random numbers and write to text file

Time:05-09

So I have to generate 100 random numbers between 1 and 100 and write them into a txt file with enter (\n) between the numbers.

Next task is to read back this txt file, count how many numbers are between 20 and 80, then write the ammount to the STDOUT. Write these numbers (the ones that are between 20 and 80) into another txt file with a comma in between the numbers.

This is the code I have come up with, kinda works, but I'm sure there is a simpler and shorter way to do it. Plus it doesn't work right for some reason, beacuse it writes some (not every) number below 10 into the file (also counts them):

import random

f = open("eredmenyek_nyers.txt", "w")
for i in range(100):
    randomlist = random.randint(1,100)
    f.write(str(randomlist)   '\n')
f.close()

db=0
f = open("eredmenyek_nyers.txt", "r")
f2 = open("eredmenyek_szort.txt", "w")
szamok = f.read()
ezt = szamok.split("\n")
xxx=len(ezt)
print(ezt)
i=0
db=0

for xxx in ezt:
    if '80' > ezt[i]:
        if ezt[i] > '20':
            db =1
            f2.write(str(ezt[i])   ',')
    i =1
print("Ennyi 20 és 80 közötti szám van ebben a listában:",db)
f.close()
f2.close()

CodePudding user response:

The part of problem due to string being compared to integers is resolved. Below code will do what the expectation is. But, as you mentioned in the question, first is to write 100 numbers to a file, post that read the file, print in STDOUT, post that write the numbers between 20 and 80 into another file... this appears as a sequence of events. You can write to both files and STDOUT in one for loop itself, if that is not an issue. I am updating so that the sequence of actions are done one after another - as is mentioned in your question.

Replace the 2nd for loop with this code....

for item in ezt:
    if item != '': # To handle last /n which will be a blank 
        if int(item) < 80 and int(item) > 20:
            db =1
            f2.write(item   ',')

CodePudding user response:

... This is the code I have come up with, kinda works, but I'm sure there is a simpler and shorter way to do it. ...

You could actually do this a bit compacter, with comprehensions, map() and .join():

from random import randint

with open("numbers.txt", "w") as file:
    file.writelines(f"{randint(1, 100)}\n" for _ in range(100))

with open("numbers.txt", "r") as fin,\
     open("filtered_numbers.txt", "w") as fout:
    numbers = [n for n in map(int, fin) if 20 < n < 80]
    print(f"Found {len(numbers)} numbers between 20 and 80.")
    fout.write(",".join(map(str, numbers)))
  • Related