In: Computer Science
Starting out with Python
Files and Exceptions - Random Number Writer, Reader, and Exception Handler
In this assignment, you will be writing a series of random numbers to a file, reading the file, and handling exceptions.
Begin by writing 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.
Next, write code that will read the random numbers from the file, display the numbers, then display the following data:
Finally, modify the program so it handles the following exceptions:
This should all be completed within ONE python scr
code:
# importing random package to create random
numbers
import random
# Taking input from the user
x = int(input("How many random numbers you want to store:
"))
# opening file in writing mode
f = open("random.txt","w")
# for loop to create x random numers
for i in range(x):
n = random.randint(1,100) # This method will create random integers
in range 1 through 100
f.write(str(n)) # converting n to string and writing to file
f.write("\n") # To write every generated random number in a new
line
f.close() # closing file
# Handling IOError exception while reading file
try:
f1 = open("random.txt","r") # now opening file in reading
mode
print("The numbers in the file are: ")
print(f1.read()) # read() method will read all lines in
file
f1.seek(0) # moving file cursor to initial
position
s = c = 0 # Initially sum s and count c will be 0
# iterating through every line in file
for num in f1:
# Handling ValueError exception
try:
s+=int(num) # converting string to integer and sum it to s
except ValueError:
print("Not a valid number")
c+=1 # incrementing count
# Printing statements
print("\nThe total of numbers is: ",s)
print("Number of random numbers read from file are: ",c)
except IOError:
print("No such file or directory")
OUTPUT
Output for IOError: Here i gave incorrect file name