Python 无法在单独的输出文件中使用for循环保存不同行中的数据
我试图将计算结果保存在输出文件中(使用python的open内置函数创建)。我的计算使用python中的for循环,我希望将所有结果保存在一个单独的输出文件中。但不幸的是,只有循环的最后一个值保存在输出文件中。为了让我的问题在下面更清楚,我正在分享我的代码Python 无法在单独的输出文件中使用for循环保存不同行中的数据,python,python-3.x,Python,Python 3.x,我试图将计算结果保存在输出文件中(使用python的open内置函数创建)。我的计算使用python中的for循环,我希望将所有结果保存在一个单独的输出文件中。但不幸的是,只有循环的最后一个值保存在输出文件中。为了让我的问题在下面更清楚,我正在分享我的代码 Nlayers = [2,3,4,5,6,7,8,9,10] e_bulk = -33.071 TE2 = [-64.883,-97.954,-131.026,-164.097,-197.169,-230.240,-263.312,-29
Nlayers = [2,3,4,5,6,7,8,9,10]
e_bulk = -33.071
TE2 = [-64.883,-97.954,-131.026,-164.097,-197.169,-230.240,-263.312,-296.383,-329.455]
area = 13.635
for i in range(len(Nlayers)):
n = Nlayers[i]
e_slab = TE2[i]
sigma1 = (e_slab - (n*e_bulk)) / (2)
sigma2 = (e_slab - (n*e_bulk)) / (2*area)
fd = open('surf_energy', 'w')
print('{0:3d} {1:13.2f} {2:15.4f}'. format(n, sigma1,sigma2),file=fd)
fd.close()
在我的输出文件中,仅保存循环最后一个值的结果(即sigma1和sigma2的值)。但我想将所有结果保存在输出文件中。有人能帮我解决这个问题吗
Nlayers = [2,3,4,5,6,7,8,9,10]
e_bulk = -33.071
TE2 = [-64.883,-97.954,-131.026,-164.097,-197.169,-230.240,-263.312,-296.383,-329.455]
area = 13.635
with open("surf_energy", 'w') as my_file: # this ensures resources will be released after the block's scope ;
for i in range(len(Nlayers)):
n = Nlayers[i]
e_slab = TE2[i]
sigma1 = (e_slab - (n*e_bulk)) / (2)
sigma2 = (e_slab - (n*e_bulk)) / (2*area)
print('{0:3d} {1:13.2f} {2:15.4f}'. format(n, sigma1, sigma2), file = my_file)
# cat surf_energy
2 0.63 0.0462
3 0.63 0.0462
4 0.63 0.0461
5 0.63 0.0461
6 0.63 0.0461
7 0.63 0.0461
8 0.63 0.0461
9 0.63 0.0461
10 0.63 0.0460