Random Number File Writer: Write a program that writes a series of random numbers to a file. Each random umber should be in range of 1 through 500. The application should let user specify how many numbers the file will hold.

Which I have.

__author__ = 'Preston Howard'

# Random Number File Writer: Program writes random numbers to a file. The numbers should range from 1 to 500.

import random

afile = open("numbers.txt", "w" )

for i in range(int(input('How many random numbers would you like?: '))):
    line = str(random.randint(1, 500))


I'm needing help with the second part of the assignment.

Analyze Number File: Write a program that reads the file written in the program1. Display all numbers stored in the file, maximum number, minimum number, and average of all numbers

__author__ = 'Preston Howard'

#Analyze Number File: Reads a file and calculates the max, min, and average of the numbers in the file.

#Get the name of a file
filename = raw_input('Enter a file name: ')
total = 0
numberlength = 0
#Open the file
infile = open(filename, 'r')

#Read values from file and compute average
for line in infile:
    print line.rstrip("\n")
amount = float(line.rstrip("\n"))
total += amount
numberlength = numberlength + 1

average = total / numberlength

#Close the file

#Print the amount of numbers in file and average

print format(average, ',.2f')

Edited by Gribouillis: Attempt to write the code in a code block

1 Year
Discussion Span
Last Post by Gribouillis

Sorry I can't get the second prgroam to post in the code tags.


I just indented them but I get a wierd answer when I run the program to calc the average

I get

Enter a file name: numbers.txt

It is because your numbers are all written on one line in numbers.txt. In the first program, replace afile.write(line) with afile.write(line + '\n').

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.