Reputation: 33
Write a program that writes a series of random numbers to a file.
The count of numbers to be generated for each execution will be randomly between 1 and 20.
The actual numbers generated will be random integers between 1 and 100
Each run of the program will display a message indicating the number of new numbers written to the file
Each run of the program will display a message indicating the number of records read from the file
You cannot count or assume to know how many records are in the
file. Use the deadline method with a loop to EOF
.
Your file read and file write must each be functions (2 functions, one for each), and each be called from main.
You must use w
mode for the first write to the file and a
or
w
mode for each time after.
User will determine whether to append to existing file or write new file.
import random
def main():
more = 'y'
while more.lower() == 'y':
random_numbers = open('Unit 4 numbers.txt', 'w')
NumtoBeWr = random.randint(1, 20)
print(NumtoBeWr, 'numbers added to output file: ')
for count in range(NumtoBeWr):
number = random.randint(1, 100)
print(number)
random_numbers.write(str(number) + '\n')
random_numbers.close()
random_numbers = open('Unit 4 numbers.txt', 'r')
# This the code to read the file
line = random_numbers.readline()
number = 0
total = 0
while line != " ":
number = int(line)
line = line.rstrip('\n')
print(number)
total = total + int(line)
number = number + number
line = random_numbers.readline()
print("The total of the numbers: "+ str (total))
print("Total count of numbers read from file: "+ str (number))
more = input("Do you want to run again to write and read more numbers. (Y/N): ")
random_numbers.close()
print("Thank for using this program")
main()
Sample output for the finish program should look like this:
Upvotes: 1
Views: 4264
Reputation: 5902
You should update your while
loop as follows:
while line:
number += int(line)
total += 1
line = random_numbers.readline().rstrip("\n")
print("The total of the numbers: " + str(total))
print("Total count of numbers read from file: " + str(number))
more = input("Do you want to run again to write and read more numbers. (Y/N): ")
That is, you should put the printing of the total counts outside of the loop. Furthermore, you should increment total
by one instead of by the number in the current line to get the total numbers generated.
Upvotes: 1