Skip to content

Instantly share code, notes, and snippets.

@espoirMur
Last active March 11, 2020 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save espoirMur/64e2218dba740d8e144668a587793947 to your computer and use it in GitHub Desktop.
Save espoirMur/64e2218dba740d8e144668a587793947 to your computer and use it in GitHub Desktop.
Read a file containing integer and return the average of the integer in the file. the file can have path to another file which contain integer.
1
2
3
4
5
another_file.txt
3
4
5
6
10
11
12
13
14
the_third_file.txt
def read_file_recursively(filename):
"""
Read a file recursively and return the
sum and the count of integer in the file
Args:
filename ([string]): path to the base file to read
Returns:
[tuple]: sum of all items in the list, the number of items
"""
sum_, len_ = 0, 0
with open(filename, 'r') as the_file:
for line in the_file.readlines():
try:
sum_ += int(line)
len_ +=1
except ValueError:
sub_sum, sub_leng = read_file_recursively(line.strip())
sum_ += sub_sum
len_ += sub_leng
return sum_, len_
if __name__ == "__main__":
sum_, len_ = read_file_recursively('a_file.txt')
print('the average is : ', sum_/len_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment