In: Computer Science
Please use Python 3
3). Write a function that writes a series of random numbers to a text file named ‘random_number.txt’. Each random number should be in the range of 1 through 500. The function should let the user specify how many random numbers the file will hold. Then write another function that reads the random numbers from the ‘random_number.txt’ file, displays the numbers, and then displays the total of the numbers and the number of random numbers read from the file. This means, you will have two functions, the first one being the file writing function and the second one being the file reading function.
Sample input & output:
Output for the first file writing function should be that you have created a txt file in your computer containing the generated random numbers. Output when you call the file reading function (e.g., I generate 5 numbers):
(Output) 36
(Output) 379
(Output) 69
(Output) 302
(Output) 301
(Output) The total of the numbers is 1087
(Output) We have read 5 numbers from the file.
Attached the code and smaple outputs. Please Upvote
First File, to create the Txt file and add the numbers
import random
file = open('test.txt','w')
count = int(input("How many numbers should be written to the file? "))
for i in range(count):
file.write(str(random.randint(1,500)))
file.write(" ")
file.close()
print("File test.txt created with {} Numbers".format(count))
Second file to read the file and output the sum of the numbers
fl = open('test.txt','r')
content = fl.read()
content = content.split()
sum = 0
for i in content:
sum += int(i)
print(i)
print("The total of the numbers is {}".format(sum))
print("We have read {} numbers from the file".format(len(content)))