我有一个30个物种的参数值数据集,我想运行一个脚本来对每个物种进行模拟。参数值当前存储在.txt文件中,其中每一行都是不同的类型,而每一列都是不同的参数值。我想做的是设置一个do -循环,它读取每个物种的相关参数值行,运行模拟脚本,并为每个物种编写输出的.txt文件。不幸的是,我对fortran并不熟悉,在do循环的每一步中,我都很难理解如何从.txt文件中读取连续行。我试着制作一个简化的脚本来测试读取步骤是否有效:
PROGRAM DRIVER
IMPLICIT NONE
INTEGER :: mm ! I forgot this line in the first version of this question
and edited to add it in
CHARACTER(7) :: species !! the first column is the species name
REAL*8 :: leaf_variable ! The next 3 columns are variable values
REAL*8 :: stem_variable !
REAL*8 :: root_variable !
OPEN (12, file = "species_parameters.txt") ! open the .txt file
DO mm = 1,30 ! set up the do loop
READ (12,*) species, leaf_variable, stem_variable, root_variable
! Read in the species-specific parameter values
WRITE (*,*) species, leaf_variable, stem_variable, root_variable
! Print the values on the screen just to show the do loop runs
ENDDO
END PROGRAM DRIVER但是当我开始编译时,我得到了错误:在文件XX的第XX行(unit = 12,file = 'species_parameters.txt') Fortran运行时错误:文件结束
我对打开和阅读这份文件有什么误解?
非常感谢您的帮助。
编辑:我想我已经缩小了我的问题。我的理解是,read()一次接受.txt文件中的一行,因此在本例中:
read(7, *) species, leaf_variable, stem_variable, root_variable
read(7, *) species, leaf_variable, stem_variable, root_variable变量应该等于.txt文件第二行中的值。相反,不管我输入read()函数多少次,变量值都等于第一行。而且,即使只有4列,我也可以用read()函数定义任意数量的变量:
read(7, *) species, leaf_variable, stem_variable, root_variable,
fake_variable1, fake_variable2, fake_variable3, fake_variable4其中,fake_variable值等于.txt文件第二行中的值。我是对read()做了什么感到困惑,还是需要做些什么来防止我的脚本将整个.txt文件作为一行读取?
编辑2:既然我已经用Unix编码使用.txt保存了我的TextWrangler文件,do循环就可以一行一行地正确读取。原始文件用Excel保存为.txt文件。这似乎解决了这个问题,但是如果有人有更好的方法来指定输入文件格式,我会很感激的。输入文件的前几行如下所示:
species1,1.2,6.54,10.9
species2,1.42,3.5,8.23
species3,0.85,2.41,4.9 发布于 2016-08-24 11:48:11
运行时错误是当您有一个可执行文件时,执行它,然后它崩溃。编译时错误是编译器无法生成可执行文件时发生的错误。
这段代码不应该编译,因为您有IMPLICIT NONE,但是没有声明整数mm。
我建议的是获取更多的信息:
program driver
use iso_fortran_env
implicit none
character(len=7) :: species
real(kind=real64) :: leaf_variable, stem_variable, root_variable
integer :: u, ioerr
character(len=120) :: iomsg
open(newunit=u, file='species_parameters.txt', action='read', status='old', iostat=ioerr, iomsg=iomsg)
if (ioerr /= 0) then
print *, "Error opening file"
print *, trim(iomsg)
stop 1
end if
do
read(u, *, iostat=ioerr, iomsg=iomsg) species, leaf_variable, stem_variable, root_variable
if (ioerr /= 0) exit ! exits the loop
write(*, *) species, leaf_variable, stem_variable, root_variable
end do
print *, trim(iomsg)
close(u)
end program driver这将始终打印“读取超过文件结束”错误,但这只是检查如何编程读取无论如何。
这应该是编译的,当您运行它时,它应该会给您一些关于哪里出了问题的信息。
https://stackoverflow.com/questions/39115375
复制相似问题