如何从dat文件中提取数据?

时间:2019-05-08 04:44:23

标签: fortran

我想使用fortran代码提取.dat文件中1,3,5,9,11,....行中的值。这是我的代码

   program one
   integer x, y, z

   open (unit=10, file='try.dat', status='old')
   open (unit=20, file='run_energy.dat', status='unknown')
   dimension time(40), energy(40)


   do y=1,13
   z=2*(y-1)
   do x=(z+1),(z+1)
   read (10,*) time(x), energy(x)
   write(20,*) time(x), energy(x)
   end do
   end do
   stop
   end


但是,我没有得到与我上面提到的行相对应的值。你能不能请任何人帮助我。

谢谢。

2 个答案:

答案 0 :(得分:0)

您需要跳过一行(虚拟读取)。像这样:

   x = 1 
   do i=1,13
     ! Read only if at correct line of 'try.dat'
     if (i == 2*(x-1)+1) then 
       read (10,*) time(x), energy(x)
       write(20,*) time(x), energy(x)
       ! Increment x 
       x=x+1
     else
       ! Skip line
       read (10,*)
     end if
   end do

亲切的问候。

答案 1 :(得分:0)

如前所述,诀窍是跳过输入文件try.dat的一行,以便仅将奇数行写入输出文件run_energy.dat

因此,如果输入文件的奇数值应保存在向量timeenergy中,则FORTRAN解决方案也可能看起来像这样:

program one
implicit none
integer, parameter :: siz = 40
integer   :: x, st
real      :: time(siz), energy(siz)
character :: line*256

open (unit=10, file='try.dat', status='old')
open (unit=20, file='run_energy.dat', status='unknown')

x = 1
read(10,'(A)',iostat=st) line
do while ((st == 0).and.(x < siz))
  write(*,*) 'x = ',x, ', line = ', trim(line)
  read(line,*,iostat=st) time(x), energy(x) 
  if (st == 0) write(20,*) time(x), energy(x)
  read(10,'(A)',iostat=st) line ! Skip one line
  if (st == 0) then   ! Read next relevant line
    x = x + 1
    read(10,'(A)',iostat=st) line 
  endif
end do
close(10)
close(20)
end

如果不需要将数据保存到这些向量中,那么解决方案就很短:

program one
implicit none
integer :: st
character :: line*256

open (unit=10, file='try.dat', status='old')
open (unit=20, file='run_energy.dat', status='unknown')

read(10,'(A)',iostat=st) line
do while (st == 0)
  write(20,'(A)') trim(line)
  read(10,'(A)',iostat=st) line ! Skip one line
  if (st == 0) then   ! Read next relevant line
    read(10,'(A)',iostat=st) line 
  endif
end do
close(10)
close(20)
end

窍门是在iostat语句中使用read来检测文件结尾或line数据与向量time和{{1}的不正确匹配}。

希望有帮助。