In: Computer Science
Write a Python program that uses function(s) for writing to and reading from a file:
a. Random Number File Writer Function
Write a function that writes a series of random numbers to a file called "random.txt". Each random number should be in the range of 1 through 500. The function should take an argument that tells it how many random numbers to write to the file.
b. Random Number File Reader Function
Write another function that reads the random numbers from the file "random.txt", displays the numbers, then displays the following data:
The total of the numbers
The number of random numbers read from the file
c. Main Function
Write a main function that asks the user about how many random number the user wants to generate. It them calls the function in a. with the number the user wants as an argument and generates random numbers to write to the file. Next, it calls the function in b.
Make sure your program works correctly.
Python code pasted below.
import random
#random number file writer function
def random_writer(n):
fw=open("random.txt","w")
for i in range(n):
#generating random numbers
rand=random.randint(1,500)
#writing to output file
r=str(rand)+"\n"
fw.write(r)
fw.close()
#random number file writer function
def random_reader(filename):
fr=open(filename,"r")
#initialize sum and count to 0
sum=count=0
while True:
line=fr.readline()
if not line:
break
else:
count=count+1
sum=sum+int(line)
fr.close()
print("Total number of numbers read from the file is ",count)
print("Sum of all random numbers in the file is ",sum)
#main program
#Reading how many random numbers to generate
n=int(input("How many random numbers to generate?"))
#calling random_writer() function
random_writer(n)
#calling random_reader function
filename="random.txt"
random_reader(filename)
Python code in IDLE pasted below for better understanding
of the indent.
Output Screen
Output file generated