Reputation:
I have this code to interpolate between the values and return Z value for specific X and Y. I am trying to open another file (world.txt) and paste the value under specific name Nz The way the file is organised is
Nx
5
Ny
0.1
Nz
0.8
I am trying to make the code to find Nz and then over write the value under it. But the value is not changing under Nz like the code is not working, Would you please suggest some ideas of how to fix it? Best Regards
import numpy as np
from scipy import interpolate
from scipy.interpolate import griddata
import itertools
from scipy.optimize import curve_fit
xx= 0.15, 0.3, 0.45, 0.5, 0.55
yy= 0.01, 0.02, 0.03, 0.04, 0.05
zz= 0.75, 0.76, 0.77, 0.78, 0.79
tck = interpolate.bisplrep(xx, yy, zz, s=0)
def givemeZ(X,Y):
return interpolate.bisplev(X,Y,tck)
## to replace the value
new_lines = []
previous_line = ''
with open('world.txt', mode = 'r') as f:
for current_line in f:
if previous_line == 'Nz':
new_lines.append(str(givemeZ(0.5,0.01)))
else:
new_lines.append(current_line)
previous_line = current_line
new_text = '\n'.join(new_lines)
Upvotes: 1
Views: 80
Reputation: 5632
Well you are not writing it back, just reading it? Als, you are not iterating over lines when you do
current_line in f:
, you'd need to do current_line in f.split('\n'): # Split on newline.
You need to do:
import numpy as np
from scipy import interpolate
from scipy.interpolate import griddata
import itertools
from scipy.optimize import curve_fit
xx= 0.15, 0.3, 0.45, 0.5, 0.55
yy= 0.01, 0.02, 0.03, 0.04, 0.05
zz= 0.75, 0.76, 0.77, 0.78, 0.79
tck = interpolate.bisplrep(xx, yy, zz, s=0)
def givemeZ(X,Y):
return interpolate.bisplev(X,Y,tck)
## to replace the value
new_lines = []
previous_line = ''
with open('world.txt') as f: # Mode 'r' is default, no need to specify.
for current_line in f.read().split('\n'):
if previous_line == 'Nz':
new_lines.append(str(givemeZ(0.5,0.01)))
else:
new_lines.append(current_line)
previous_line = current_line
new_text = '\n'.join(new_lines)
open('world.txt', 'w').write(new_text) # Will save the text to file.
Upvotes: 1