0

I'm trying to write a program that will open a file named "data.dat". This file contains an unknown number of values that I need to have read and averaged together and is written such that each line has one value. I need to have the data in this file be averaged and printed to the screen. I'm having trouble just getting started with this and any help would be appreciated. Thanks

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by pythopian
0

hi,
here's a small example on opening and reading from a file.

Suppose you have a file "data.dat" containing the numbers from 1 to 7 like this
1
2
3
4
5
6
7

f = open( "data.dat", "r" )
lines = f.readlines() # returns every line in the file in a list
for line in lines:
    print line.strip() #get rid of new line character
f.close()

>>> 
1
2
3
4
5
6
7
>>>

now you can do computation with the numbers but remember that they are all strings so you need to do a type conversion first :)

hope this helps :)

0
numbers = map(float, file('data.dat', 'rt').read().split())
average = sum(numbers) / len(numbers)

For a case like masterofpuppets' above:

>>> average
4.0

Note the use of float , not int , to cover floating point numbers in 'data.dat'.

Edited by pythopian: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.