# Thread: Python Program to Calculate Avg of Numbers in a Text File

1. ## Python Program to Calculate Avg of Numbers in a Text File

Coded in IDLE. Project was to create a program that read the contents of a .txt file and calculated the avg of all numbers in the file. This was to be done using 2 Higher - Order Functions (mapping and reducing) of your choice. I've test ints and decimals with this program and it has worked perfectly, have not tried putting strings into the test file but I'd assume it wouldn't work for obvious reasons.
Code:
```import functools

input_File = input('Name of file: ') #ask user for name of file
file = open(input_File, 'r') #open file

file = file.split() #put numbers into list

file = list(map(float, file)) #convert list into floats
file_Sum = functools.reduce(lambda x, y: x + y, list(file)) #grabs sum of file

print(file_Sum / len(file)) #average function using file sum from reduce fuction```

2. ## The Following User Says Thank You to Matthew For This Useful Post:

mburhm (07-02-2021)

3. Code:
`file = list(map(float, file)) #convert list into floats`
You can to implement a Try/Except block inside your map function at the point it does the data type conversion. If it throws an exception then just return null or 0 and suppress the error message.

4. ## The Following User Says Thank You to Bababam For This Useful Post:

Matthew (02-08-2021)

5. Code:
```sum = 0
input_File = input('Name of file: ')
file = open(input_File, 'r')

file = file.split()
total = len(file)

for num in file:
sum += int(num)

print (f"Average number in {file} is {sum/total}")```

6. good project

7. Yo I like this ,very nice !

good project