Write a Python program that writes a series of random numbers to a file. Each ra
ID: 3538575 • Letter: W
Question
Write a Python program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 100. The application should let the user to specify how many random numbers the file will hold.
I was wondering if I can get also get help with the continuation of this exercise:
It stated if I can make another python program that reads the random numbers from the file made from the exercise above then, display the numbers, and then display the following data:
The total of the numbers
The number of random numbers read from the file
Thanks again
Explanation / Answer
#Using python2
#save both programs as separate files, in the same folder; then run each one after the other
#Random Number File Writer
import random
n=input("Enter number of random numbers to generate:")
n2=int(n)
a_file=open('randomNumbers.txt','w')
for i in range(0,n2):
s=random.randint(1,100)
s2=str(s)+" "
a_file.write(s2)
a_file.close()
#Random Number File Reader
n=0
sum=0
a_file=open('randomNumbers.txt')
for a_line in a_file:
s=a_line.strip().split()
n=n+len(s)
for num in s:
print(num)
sum=sum+int(num)
a_file.close()
print("The total of the numbers is: "+str(sum))
print("The number of random numbers read from the file is: "+str(n))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.