2014-11-24 89 views
0

我有興趣將一個三維數組保存爲一個txt文件。 具體來說,我想能夠保存(u[0,:], u[1,:], u[2,:])作爲array0.txt (u[1,:], u[2,:], u[3,:])作爲array1.txt和(u[2,:], u[3,:], u[4,:])作爲array2.txt等。將numpy數組保存爲txt文件[Beginner]

但是,我遇到了2個問題。

  1. 我不知道如何去創造這個節能循環
  2. 當我保存三行到一個txt文件,我的數組中的元素不會被保存成三條線,但它們揉成一起。

這裏是我的代碼,並感謝你:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

dx=0.06 #space incrementB 
dt=0.03 #time increment # Make sure time increment 
          # is smaller than space increment 
tmin=0.0 # initial time 
tmax=50.0 # simulate until 
xmin=-100.0 # left bound 
xmax=100.0 # right bound...assume packet 
      # never reaches boundary 
c = 1.0 # speed of sound 
rsq=(c*dt/dx)**2 #appears in finite diff sol for damped and linear damped 
k = 10 
w = 1/(1+ k*dt) #appears in finite diff sol for linear damped 
amplitude = 10 

nx = int((xmax-xmin)/dx) + 1 #number of points on x grid 
nt = int((tmax-tmin)/dt) + 2 #number of points on t grid 
u = np.zeros((nt,nx)) #solution to WE 


def init_fn(x): 
    val = amplitude*(np.exp(-(x**2)/25)) 
    # If you decrease the amplitude by 10, the total PE 
    # decreases by 100 #Big potential amp = 1, 2 mag small amp=1/10 
    if val<.0001: 
     return 0.0 
    else: 
     return val 

for a in range(0,nx): 
    u[0,a]=init_fn(xmin+a*dx) 
    u[1,a]=u[0,a] 

#simulate dynamics 
for t in range(1,nt-1): 
    for a in range(1,nx-1): 
     u[t+1,a] = 2*(1-rsq)*w*u[t,a]+ u[t-1,a]*w*(k*dt-1) +rsq*(u[t,a-1]+u[t,a+1])*w 


np.savetxt('array0.txt', (u[0,:],u[1,:],u[2,:0]), 
      delimiter=' ', fmt='%.2e') # X is an array 
f1 = open('array0.txt', 'r') 

print f1 

for line in f1.readlines(): 
    print line, 

這裏是我的array0.txt的輸出:

`enter image description here

+0

不應該'(U [0 ,u [1,:],u [2,:0]),'be'(u [0,:],u [1,:],u [2,:]), – Marcin 2014-11-24 01:53:11

+0

是的,我的問題出現了錯誤。它現在已經修復。但是有沒有人對我提出的解決方案有了深入的瞭解?謝謝! – soccerboyz9341 2014-11-24 02:01:20

回答

1

你應該能夠訪問的所有組您的u連續3行如下:

for row1, row2, row3 in zip(u[0::,:],u[1::,:],u[2::,:]): 
    print(row1, row2, row3) 
    print("\n") 
    # or write them to one file, or files. 

快速測試:

u = np.array([[1,2,3,4,5], [5,6,7,8,9], [10,11,12,13,14], [13,23,33,43,53], [54,64,74,84,94], [105,115,125,135,145]]) 

for row1, row2, row3 in zip(u[0::,:],u[1::,:],u[2::,:]): 
    print(row1, row2, row3) 
    print("\n") 

給出:

[1 2 3 4 5] [5 6 7 8 9] [10 11 12 13 14] 


[5 6 7 8 9] [10 11 12 13 14] [13 23 33 43 53] 


[10 11 12 13 14] [13 23 33 43 53] [54 64 74 84 94] 


[13 23 33 43 53] [54 64 74 84 94] [105 115 125 135 145] 

要保存在單獨的文件中的行,每個迴路,可以使用:

idx = 0; 
for row1, row2, row3 in zip(u[0::,:],u[1::,:],u[2::,:]): 
    print(row1, row2, row3) 
    np.savetxt('array{:03d}.txt'.format(idx), 
       (row1, row2, row3), 
       delimiter=' ', fmt='%.2e') 
    idx = idx + 1 
+0

你好@Marcin感謝你的回覆。有效。但我想知道如何去做,寫一個for循環,以便每次運行循環時將三行保存到一個數組#.txt文件中?任何建議將不勝感激。謝謝! – soccerboyz9341 2014-11-24 02:13:23

+0

我修改了答案。 – Marcin 2014-11-24 02:32:15