Python Forum
Finding the average of numbers in a txt file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Finding the average of numbers in a txt file
#1
This is the assignment: Write a program that read numbers from a text file named "data.txt" and store the average in a second file named "average.txt". The numbers are line separated (each line in the file contains exactly one number.) You will have to create the file data.txt for testing purpose.

I will post what I have thus far. I believe I am way over-thinking it, but I've been trying to figure this out for a couple of hours now. It is giving me the error that num_list is not defined. I had it "defined" before, but it was only returning the first number in the data.txt file.
The data.txt file consists of these numbers:
379
99
7
380
907
567
988
610
223
865
192
138
503
817
585

import math

def load_numbers(filename):
    
    num_list = []

    with open('data.txt', 'r') as f:
        for line in f:
            num =  line.strip()
            num_list += [num]
            return (num_list)
    
def main():
    load_numbers('data.txt')
    print(num_list)
    
main()
    
Reply
#2
  • num is a string, you want it to be an int. How do you do that?
  • num_list is a list.
    to add a cell to a list, you append
  • you don't need math.
  • since you are returning the list in load_numbers,
    you need to assign the return value to something you can do this like:
    value = function()
  • when you print num_list, you should print the sum of num_list. Think how to do that.
  • finally you have to write the sum to a new file.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,369 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  Convert list of numbers to string of numbers kam_uk 5 2,935 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  numbers in list - max value and average stewie 2 2,777 Apr-01-2020, 06:25 PM
Last Post: buran
  finding p's in words of a multi-line text file johneven 5 4,269 Jun-24-2019, 03:41 PM
Last Post: ThomasL
  Finding average in dictionary using for loop Rae 4 14,487 May-26-2019, 12:06 PM
Last Post: DeaD_EyE
  reading text file and writing to an output file precedded by line numbers kannan 7 10,247 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  To extract a specific column from csv file and compute the average vicson 2 8,066 Oct-20-2018, 03:18 AM
Last Post: vicson
  Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 4,054 Dec-05-2017, 09:48 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020