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

Recommended Answers

All 3 Replies

Member Avatar for masterofpuppets

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 :)

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'.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.