219k views
5 votes
Write In Python

Write a program that writes a series of random numbers to a file called rand_num. Each random number should be be in the range of 1 to 500. The application should allow the user to specify how many numbers the file will hold. Then write a program that reads the numbers in the file rand_num and displays the total of the numbers in the file and the number of random numbers in the file.

1 Answer

1 vote

Answer:

Here's a Python program that writes a series of random numbers to a file and then reads the numbers from the file and displays the total and the number of numbers in the file:

import random

# Function to write random numbers to a file

def write_random_numbers(filename, num_numbers):

with open(filename, "w") as file:

for i in range(num_numbers):

random_number = random.randint(1, 500)

file.write(str(random_number) + "\\")

print("Random numbers written to file:", filename)

# Function to read the numbers from a file and display the total and count

def read_random_numbers(filename):

total = 0

count = 0

with open(filename, "r") as file:

for line in file:

number = int(line.strip())

total += number

count += 1

print("Total of numbers in the file:", total)

print("Number of random numbers in the file:", count)

# Main program

num_numbers = int(input("Enter the number of random numbers to generate: "))

filename = "rand_num.txt"

write_random_numbers(filename, num_numbers)

read_random_numbers(filename)

User Anand Natarajan
by
7.6k points