简体   繁体   中英

Changing a text file line by line?

I am attempting to replace the first column of a .txt file with a new value calculated from the previous line and using data in the current line. I would like to preserve all columns except the first column. Below is what I currently have, however I am unsure how to replace the first column:

Tb = 264.0
K1 = 488.12
K2 = 0.4685
cp = 2100.
rho = 920.
K0 = K1/Tb+K2
kappa = K0/(rho*cp)

i=1
correct = (np.loadtxt("nusselt.txt")[i-1,0])+((np.loadtxt("nusselt.txt")[i,9])*((np.loadtxt("nusselt.txt")[i,8])**2)/(kappa*3600*24*365*(10**6)))
print(correct)
while i<(max(np.loadtxt("nusselt.txt")[:,10])):

    correct = correct+((np.loadtxt("nusselt.txt")[i,9])*((np.loadtxt("nusselt.txt")[i,8])**2)/(kappa*3600*24*365*(10**6)))
    print(correct)
    i+=1

An example of the .txt file I am using is below.

0.0006621671 0.8945038362 0.0000000000 0.1721768200 0.0807264003 72.3204864794 35306.3184418046 5004.8115858572 0.0010000000 0.0010000000 1.0000000000 
0.0009277460 0.9191163858 0.0000000000 0.1767442344 0.0804871826 74.8408206748 35347.0063156642 5006.7334039793 0.0004000000 0.0014000000 2.0000000000 
0.0011937393 0.8884819376 0.0000000000 0.1707877101 0.0809770939 71.3448542427 35388.0400666959 5008.6700659051 0.0004000000 0.0018000000 3.0000000000 
0.0014601443 0.8978641464 0.0000000000 0.1725244630 0.0809949578 72.2070954963 35429.1476976574 5010.6087141754 0.0004000000 0.0022000000 4.0000000000 
0.0017269683 0.8764531166 0.0000000000 0.1683451774 0.0813451815 69.6863077136 35470.5221963013 5012.5584343836 0.0004000000 0.0026000000 5.0000000000 

Firstly, you only need to load the file in once. Currently, each time you use np.loadtxt it's having to re-read in the file. To achieve what you want I think you could do something like:

Tb = 264.0
K1 = 488.12
K2 = 0.4685
cp = 2100.
rho = 920.
K0 = K1/Tb+K2
kappa = K0/(rho*cp)

# load the data file in
data = np.loadtxt("nusselt.txt")

# loop over the data
for i in range(1, len(data)):
    # update the first column
    data[i, 0] = data[i-1,0] + (data[i,9]*data[i,8])**2/(kappa*3600*24*365*(10**6))

print(data)

# save it to a file again
np.savetxt("nusselt_new.txt", data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM