Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To answer your question, as I understand it, in three parts: </p> <p><em>How to read the file in</em></p> <p>in your example you use</p> <blockquote> <p>infile.read()</p> </blockquote> <p>which reads the entire contents of the file into a string and takes you to the end of file. Therefore the following </p> <blockquote> <p>infile.readlines()</p> </blockquote> <p>will read nothing more. You should omit the first read().</p> <p><em>How to compute the mean</em></p> <p>There are many ways to do this in python - more or less elegant - and also I guess it depends on exactly what the problem is. But in the simplest case you can just sum and count the values as you go , then divide sum by count at the end to get the result:</p> <pre><code>infile = open("d.dat", "r") total = 0.0 count = 0 for line in infile.readlines(): print ("reading in line: ",line) try: line_value = float(line) total += line_value count += 1 print ("value = ",line_value, "running total =",total, "valid lines read = ",count) except: pass #skipping non-numeric lines or characters infile.close() </code></pre> <p>The try/except part is just in case you have lines or characters in the file that can't be turned into floats, these will be skipped.</p> <p><em>How to write to the .dat file</em> </p> <p>Finally you seem to be asking how to write the result back out to the d.dat file. Not sure whether you really need to do this, it should be acceptable to just display the result as in the above code. However if you do need to write it back to the same file, just close it after reading from it, reopen it for writing (in 'append' mode so output goes to the end of the file), and output the result using write().</p> <pre><code>outfile = open("d.dat","a") outfile.write("\naverage = final total / number of data points = " + str(total/count)+"\n") outfile.close() </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload