37.6k views
4 votes
Write a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 1000. The application should let the user specify how many random numbers the file will hold.

1 Answer

3 votes

Answer:

The programming language is not stated;

I'll answer this question using python programming language

The program starts here (Lines written in bold are comments and are used for explanatory purpose)

#This line imports the random module into the program

import random

#This line prompts the user to enter the filename

filename = input("Enter file name: ")

#This line prompts the user to enter the number of random numbers to generate

num = int(input("Number of random numbers: "))

#This line adjusts the filename to a .txt file

filename = filename+".txt"

#This line checks if the filename exists; if yes, it creates and open a new file and if otherwise, it uses the existing filr

f = open(filename,'a+')

#This line iterates through the number of random to generate

for i in range(1,num+1):

#This line generates random number within the range of 1 to 1000

n = random.randint(1,1000)

#This line prints the generated random number to file

print(n, file = f)

#This line closes the created file

f.close()

User Raoof Naushad
by
6.6k points