如何将数据写入TXT文件中的特定位置?

时间:2011-11-10 05:14:33

标签: file fortran

我想要更改文本文件的一部分。该文件的内容如下:

PLANE
CV = 1.4, PRINT = 1
Ks = 3.17, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
PLANE

我想用随机数替换ks=3.17部分。更具体地说,文本文件是另一个可执行文件的输入,我想修改Ks值,运行可执行文件,再次修改Ks值,依此类推。

2 个答案:

答案 0 :(得分:0)

可能有更好的方法,但这有效。它会写入一个新的输出文件,将Ks值更改为9.99。

Program modify_value

implicit none

character(len=100) :: row
integer :: j
real :: Ks

Ks = 9.99

open(unit=1,file='data.txt',status='old')
open(unit=2,file='data_modified.txt',status='unknown')

do j=1,4
  read(1,'(a)') row
  if (j==3) then
    write(2,'(a,F5.2,a)') row(1:4), Ks, trim(row(10:))
  else
    write(2,'(a)') trim(row)
  end if
end do

close(1)
close(2)

End Program

答案 1 :(得分:0)

你有充分的理由使用fortran完成这项任务吗?您在上一段中描述的任务可以使用其他语言来完成,而不是喧嚣。例如,如果您编写如下的python脚本,

import os, random

# repeat 10 times
for i in range(10):

    # generate random Ks with Normal distribution, mean=3.17, stdev=1
    ks = random.normalvariate(3.17,1)

    # write input file
    with open('inp.txt','w') as f:

        f.write( 
"""PLANE
CV = 1.4, PRINT = 1
Ks = %4.2f, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
PLANE""" % ks )


    # run the program
    os.system("a.exe")

给出样本fortran程序,

program test
  character(len=80) :: line
  open(10,file='inp.txt',status='old')
  do i=1,4
  read(10,'(a)') line
  write(*,*) trim(line)
  enddo
end program

你会得到

$ python test.py
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 1.21, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 3.08, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 4.55, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 4.10, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 2.24, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 4.62, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 2.76, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 2.69, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 4.58, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE
 PLANE
 CV = 1.4, PRINT = 1
 Ks = 3.32, G = 120.67, DIST = 0.34, POR = 0.456, ROCK = 0.3
 PLANE