1

I'm learning how to use files in python, and I'm having a hard time understanding how to code them. My prompt is to assume a file containing a series of integers is named numbers.txt and exists on the computer’s disk. Write a program that calculates the average of all the numbers stored in the file. I've created a notepad file called numbers.txt, and I put the numbers 5, 7, 8, 9, 20 all on separate lines, in that file and saved it as such. Here is my code down bellow.

def main():

    file_numbers = open('numbers.txt', 'r')
        
    num1 = int(file_numbers.readline(1))
    
    num2 = int(file_numbers.readline(2))
    
    num3 = int(file_numbers.readline(3))

    num4 = int(file_numbers.readline(4))

    num5 = int(file_numbers.readline(5))

    file_numbers.close()

    total = (num3 + num2 + num3 + num4 + num5)

    average = total / 5

    print(f'The numbers are: {num1}, {num2}, {num3}, {num4}, {num5}')

    print (f'Their average is: {average}' )
    
main()

My output is

The numbers are: 5, 5, 66, 77, 220
Their average is: 86.8

Where is the computer getting these numbers? How can I change my code in order for it to output the correct numbers and the correct average?

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
  • 4
    As a side note, it's generally best to using a [context manager](https://docs.python.org/3/reference/datamodel.html#context-managers) when opening files. See also [What is the python "with" statement designed for?](https://stackoverflow.com/q/3012488/11082165) – Brian61354270 Mar 14 '23 at 00:27
  • As a side-note: There's no need to hardcode the number of lines. You can do `nums = [int(line) for line in file_numbers]` to read any number of numbers into a `list` of `int`s, then `average = sum(nums) / len(nums)` to compute the average (without hardcoding exactly how many lines to expect), and `print('The numbers are:', ', '.join(map(str, nums)))` to print (again, without knowing the exact number of lines). – ShadowRanger Mar 14 '23 at 01:51

3 Answers3

2
num1 = int(file_numbers.readline(1))
                        ...      2
                        ...      3
                        ...      4
                        ...      5

That's just bizarre. No, please don't do that. The size argument specifies max number of characters to read, not which line you are on.

Omit the arg, and life will be good.

https://docs.python.org/3/library/io.html#io.IOBase.readline


    total = (num3 + num2 + num3 + num4 + num5)

If you run this through the pep8 black checker, the "extra" ( ) parens will go away.

What's more important is you meant to start with num1 rather than num3.

To avoid such difficulties in future, consider using a datastructure like a five-element list.

For example, having constructed

    lst = [num1, num2, num3, num4, num5]

we can conveniently refer to sum(lst).

J_H
  • 17,926
  • 4
  • 24
  • 44
  • Thank you! I definitely misunderstood how to use "num1 = int(file_numbers.readline(1))" 100%. I appreciate the feedback and help! – elizabethgleigh Mar 14 '23 at 00:46
0

Here is a simple two-liner:

Note: requires Python 3.8+ due to the walrus := operator

with open('sample.txt') as f:
    average = sum(lines := [int(l) for l in f]) / len(lines)

Print out results with:

print(f'The numbers are: {", ".join(map(str, lines))}')
print(f'Their average is: {average}')

Then we have:

The numbers are: 5, 7, 8, 9, 20
Their average is: 9.8
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
-1

I made a couple of edits to (1) close the file when we're done with it and (2) make the code able to handle any amount of numbers in the text file.

def main():
    numbers = []
    with open('numbers.txt', 'r') as file_numbers:
        # using a context manager automatically closes the file at the end of the `with` block

        for line in file_numbers:
            # iterate through each line in the file
            # adding each number to the end of the numbers list
            number = int(line)
            numbers.append(number)

    total = sum(numbers)
    average = total / len(numbers) # use the length of the numbers list as the divisor

    print(f'The numbers are: {numbers}')
    print(f'Their average is: {average}')

main()

Output

The numbers are: [5, 7, 8, 9, 20]
Their average is: 9.8
cstoltze
  • 426
  • 1
  • 4
  • 10