Finding numbers in file | Sololearn: Learn to code for FREE!


Finding numbers in file

I have a file which contains some numbers how could I take this numbers and get the average?

11/12/2019 9:51:39 PM

محمد اسماعيل

4 Answers

New Answer


First of all, you have to define how the data is stored. Are the numbers separated by ',' or by spaces... That's the most important : knowing how your numbers are stored in the file. I assume all your numbers are written on one line and separated by ','. - open the file - read the fisrt line as a string - split this string at each ',' ; it returns a list containing all the numbers as strings - convert all elements of that list into int - print the sum of the list divided by the length of the list


Complete "Exceptions and Files" section in your python course, then you will know how to read data from the files. After reading the data, do whatever you want to do with data.


ahhh..... you'll need to use regular expression --"findall" .... sample data would be useful. What have you been able to do so far? I've had a go and managed to get it done in three lines of code (four if you include the import re statement) it's easier than you think. correction;- Two lines of code if you import statistics module too.


They are separated by spaces The text has lines contains letters and numbers