-2

I want write a program that asks the user for the name of a file containing numbers in each line and prints the average of each line. The numbers in the file are separated by spaces. The .txt file is the following:

    23 55 12 90 42
    56 33 11 76 34
    91 42 45 88 23
    90 114 78 117 89
    116 64 25 77 33

I can open and read a file with

    f = open(input("File: "))
    for i in f:

and with the starting for loop I can loop through the lines. But I don't know how I can only the first line, add the numbers in the first line and then divide it by 5 to get the average and then do it for the remaining lines. How can I do it?

kankan77
  • 13
  • 1
  • 2

5 Answers5

1

consider your text file name is "numbers.txt" you can use the readLines() function like:

file1 = open('numbers.txt', 'r')
Lines = file1.readlines()
count = 0

for line in Lines:
    count = 0
    sum_number = 0
    for i in line.split(' '):
        count += 1
        sum_number += int(i)
    print("avg: {}".format(sum_number / count))

the output will be:

avg: 44.4
avg: 42.0
avg: 57.8
avg: 97.6
avg: 63.0
0

Adapted from How to read numbers from file in Python?

If you are ok with using Numpy, you could use:

with open('file.txt') as f:
    array = [[int(x) for x in line.split()] for line in f]

np.mean(array, axis=1)
0

Using basic Python

with open(input('File: ')) as f:
    for line_no, line in enumerate(f):                     # enumerate provides data and line number for each line
        numbers = [int(i) for i in line.rstrip().split()]  # convert each line to numbers
        avg = sum(numbers)/len(numbers)                    # using definition of average
        print(f'Avg. of line {line_no} is {avg}')          # print line number and average
        
DarrylG
  • 16,732
  • 2
  • 17
  • 23
0
f = open(input("File: "))

for i in f.readlines():
    line = list(map(int, i.strip("\n").split()))
    average = sum(line) / len(line)
    print(average)

Basically, the first line gets the file name.

The third line starts a for loop that loops through f.readlines, which is basically a list of every line in the file.

The fourth line is a bit confusing. i.strip("\n").split() removes the \n in every line, and splits the list by space, so you get ['23', '55', '12', '90', '42']. Then, list(map(int, turns each value in this list from a string into an integer.

Finally, the last line gets the average. sum(line) adds up every element in the list we just made. Then, len(line) gets the number of values in the list. Together, when sun(line) is divided by len(line) you get the average, which is then printed.

The Pilot Dude
  • 2,091
  • 2
  • 6
  • 24
0

A possible solution is:

name = input('File: ')

with open(name, 'r') as f:
    lines = f.readlines()

line_nr = 0
for line in lines:
    line_nr += 1
    numbers = line.strip('\n').split(' ')
    sum_numbers = 0
    total_numbers = len(numbers)
    
    for number in numbers:
        int_number = int(number)
        sum_numbers += int_number
        

    

    print(f'The average of line {line_nr} is:', sum_numbers/total_numbers)

Output:

The average of line 1 is: 44.4
The average of line 2 is: 42.0
The average of line 3 is: 57.8
The average of line 4 is: 97.6
The average of line 5 is: 63.0
joao_lucas
  • 48
  • 1
  • 6