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.

Respuesta :

import random

def random_number_file_writer(nums):

   f = open("random.txt", "w")

   i = 0

   while i < nums:

       f.write(str(random.randint(1,500))+"\n")

       i += 1

   f.close()

def random_number_file_reader():

   f = open("random.txt", "r")

   total = 0

   count = 0

   for x in f.readlines():

       total += int(x)

       count += 1

   print("The total of the numbers is "+str(total))

   print("The number of random numbers read from the file is "+str(count))

def main():

   random_number_file_writer(int(input("How many random numbers do you want to generate? ")))

   random_number_file_reader()

main()

I hope this helps!

ACCESS MORE