SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Files And Exceptions
Exercise:
Programming Exercises
Question:7 | ISBN:9780132576376 | Edition: 2

Question

Random Number File Writer
Write a 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 specify how many random numbers the file will hold.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Random Number File Writer Python Code:

#Header random section
import random
#A series of random numbers to a file. Each random number should be in the range of 1 through 100.
def writeRandomNums(inputFile, count):
    with open(inputFile, 'w') as file:
        for _ in range(count):
            random_number = random.randint(1, 100)
            file.write(str(random_number) + '\n')

inputFile = input("Enter the name of the file to create: ")
count = int(input("Enter the number of random numbers to generate: "))

writeRandomNums(inputFile, count)

print(f"{count} random numbers have been written to '{inputFile}'.")

Executed Output:

Enter the name of the file to create: numbers.txt
Enter the number of random numbers to generate: 50
50 random numbers have been written to 'numbers.txt'.

Displayed data in "numbers.txt' after executed program code:

83
28
93
28
41
46
55
70
2
3
83
47
30
19
2
69
83
73
88
45
81
23
77
17
9
63
1
93
8
86
11
36
88
40
4
35
12
23
77
59
16
66
85
55
30
51
79
14
62
21

 

0 0

Discussions

Post the discussion to improve the above solution.