python:打开另一个文件以粘贴输出值
我有这段代码在值之间插值,并返回特定X和Y的Z值。我正在尝试打开另一个文件(world.txt)并将该值粘贴到特定名称Nz下 文件的组织方式是python:打开另一个文件以粘贴输出值,python,replace,Python,Replace,我有这段代码在值之间插值,并返回特定X和Y的Z值。我正在尝试打开另一个文件(world.txt)并将该值粘贴到特定名称Nz下 文件的组织方式是 Nx 5 Ny 0.1 Nz 0.8 我试图使代码找到Nz,然后在它下面重写值。但是Nz下的值不会改变,就像代码不起作用一样, 请你提出一些解决办法好吗? 致意 import numpy as np from scipy import interpolate from scipy.interpolate import griddata import i
Nx
5
Ny
0.1
Nz
0.8
我试图使代码找到Nz,然后在它下面重写值。但是Nz下的值不会改变,就像代码不起作用一样,
请你提出一些解决办法好吗?
致意
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)
你不是在写,只是在读?Als,当您这样做时,您不是在迭代行
f中的当前行:
,您需要在f.split('\n')中执行当前行:#在newline上拆分。
您需要执行以下操作:
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.
是否要编辑文件中的一行?是的,代码应提供一个值并将其放入该文件中。是否尝试从“world.txt”读取Nx和Ny,并将Nz值写回“world.txt”?否,我试图让代码找到Nz,然后在其下重写该值。这将删除文件中的所有内容,而不是覆盖一个值。那么,代码中的某些内容是错误的,但是如果要保存结果,您肯定需要在最后运行open().write()。我明白了。您正在做:
以open('world.txt',mode='r')作为f:对于f:
中的当前_行,您应该做以open('world.txt',mode='r')作为f:对于f.split('\n')中的当前_行:
,如果您想迭代行,我更新了答案。否,打开文件后缺少f.split('\n')。是的,很抱歉,您也没有读取文件。更新我的答案时,需要执行f.read().split(“\n”)