2017-05-19 166 views
1

我想在Fortran中讀取我用Python編寫的二進制文件。 我知道如何做相反的事情(編寫Fortran並閱讀Python)閱讀用Python編寫的Fortran二進制文件

這就是我如何在Python中編寫我的文件(.dat).txt。被檢查的人數

ph1 = np.linspace(-pi, pi, num=7200) 

f_ph = open('phi.dat', 'w') 
f_ph.write(ph1.tobytes('F')) 
f_ph.close() 

f_ph = open('phi.txt', 'w') 
for aaa in ph1: 
    ts = str(aaa) + '\n' 
    f_ph.write(ts) 
f_ph.close() 

,而不是我的Fortran代碼如下所示:

 program reading 

      real realvalue 
      integer i 

     i=1 

     open(unit=8,file='phi.dat',form='UNFORMATTED',status='OLD') 


     do 
      read(8,END=999,ERR=1000) realvalue 
      write(*,'(1PE13.6)') realvalue 
      i = i + 1 
     enddo 

999  write(*,'(/"End-of-file when i = ",I5)') i 
     stop 

1000 write(*,'(/"ERROR reading when i = ",I5)') i 
     stop 

     end program reading 

我仿照這個例子中這個程序http://numerical.recipes/forum/showthread.php?t=1697

但是,如果我運行它,我得到這個:

[gs66-stumbras:~/Desktop/fortran_exp] gbrambil% ./reading 
-2.142699E+00 

End-of-file when i =  2 

回答

3

關於Python,您必須添加二進制選項打開,即

import numpy as np 
pi = np.pi 
ph1 = np.linspace(-pi, pi, num=7200) 

f_ph = open('phi.dat', 'wb') 
f_ph.write(ph1.tobytes('F')) 
f_ph.close() 

f_ph = open('phi.txt', 'w') 
for aaa in ph1: 
    ts = str(aaa) + '\n' 
    f_ph.write(ts) 
f_ph.close() 

由於涉及FORTRAN你必須考慮到:

  • numpy的默認基礎類型(很可能)Float64對應的Fortran real(kind(1.d0))

  • 因爲Fortran通常在讀/寫之前和之後跳過/添加記錄標記,所以必須禁用此行爲將access="stream"添加到打開語句

 
program reading 
real(kind(1.d0)) :: realvalue 
integer :: i 

i=1 

open(unit=8,file='phi.dat',form='UNFORMATTED',status='OLD', access="stream") 

do 
    read(8,END=999,ERR=1000) realvalue 
    write(*,'(1PE13.6)') realvalue 
    i = i + 1 
enddo 

999  write(*,'(/"End-of-file when i = ",I5)') i-1 
stop 

1000 write(*,'(/"ERROR reading when i = ",I5)') i-1 
stop 

end program reading