the program must read the contents of input.txt, find the min, max and average and then print out the results in a new file.

here is my code so far

# to open the txt file in read and write mode
text_file = open('input.txt', 'r+')

# we now create a list for the numbers in the program
number_list = []

# now we create a loop that loops over each line in the txt file
for line in text_file:
    number_list.append(line.split(','))

3 Answers

0
nassim On

you need first to convert your array to int and then use max, min and sum, len functions :

number_list_int = [int(i) for i in number_list[0]]

print(min(number_list_int))
print(max(number_list_int))
print(sum(number_list_int)/len(number_list_int))
1
Devesh Kumar Singh On

To begin with, you want to use a context manager like with to take care of opening and closing the file automatically

Then you can use python builtins min max and sum to calculate minimum, maximum and average respectively

#Open the txt file in read and write mode, and get all integers in file
number_list = []
with open('file.txt', 'r') as fp:
    number_list = [int(item) for item in fp.readlines()]

#Calculate minimum, maximum and average and print it
minimum = min(number_list)
maximum = max(number_list)
average = sum(number_list)/len(number_list)

print('min:', minimum, 'max:', maximum, 'avg:', average)

So if input.txt looks like this (one number per line):

1
2
3
4
5
6
7
8
9
10

The output will be

min: 1 max: 10 avg: 5.5
0
shubham On

I am assuming file contains integer values separated by newline

>>> # Read file into an array and convert string form integers to int
>>> fd = open("nums")
>>> nums = map(int, fd.read().strip().splitlines())
>>> fd.close()
>>> nums
[12, 15, 5, 89, 2, 3, 5, 6, 11]

>>> # Following functions are self explanatory
>>> max(nums)
89
>>> min(nums)
2
>>> sum(nums)
148
>>> len(nums)
9

>>> # write to file
>>> fd = open("result", "w")
>>> fd.write("max: " + str(max(nums)))
>>> fd.write("\nmin: " + str(min(nums)))
>>> fd.write("\navg: " + str(sum(nums) / len(nums)))
>>> fd.close()