I have a file named file.in that contains 6 columns of data. One of the columns contains the mean and another contains the error. File.in is around 900 lines long with a different value for mean and error in each line. Example:
xxxx xxxxx xxxxx mean1 error1 xxxx
xxxx xxxxx xxxxx mean2 error2 xxxx
xxxx xxxxx xxxxx mean3 error3 xxxx
I would like to use np.random.normal to create a random value using the mean and error for each line. Then, I would like to place the new value that np.random.normal generates into the file like this:
xxxx xxxxx xxxxx newmean1 error1 xxxx
xxxx xxxxx xxxxx newmean2 error2 xxxx
xxxx xxxxx xxxxx newmean3 error3 xxxx
I need to also write over everything else that is in file.in. So basically copy file.in but with a new value for the means based on the error and mean from file.in.
The following code works fine when it comes to changing just two lines. The problem is that I need to do this for over 900 lines all with different values. And the top of the file has about 11 lines of code that I need to copy over before I start replacing the values and iterating. Maybe it’s possible to save data to columns but there aren’t any headers in the file.
I tried this:
<#mean1 = 12
#error1 = 2
#mean2 = 14
#error2 = 1
chan = np.random.noraml(mean1, error1, N=10)
chan2 = np.random.normal(mean2, error2, N=10)
for k in zip(chan, chan2):
with open('file.in', 'rt') as fin, open('file.out', 'w') as fout:
for i, line in enumerate(fin, 1):
if i == 12:
modified = line.replace(" 12.0", str(k))
fout.write(modified)
if i == 13:
modified = line.replace( "14.0", str(k))
fout.write(modified)
else:
fout.write(line)
Allyand Camshow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.