我们如何逐行读取特定文件,同时跳过其中的某些列?
例如,我有一个文本文件,其中有数据,分为5列,但我只需要读取两列,它们可以是前两个或任何其他随机组合(我的意思是,需要一个可行的解决方案)与任何列的组合,如第一和第三列).
代码是这样的
open(1, file=data_file)
read (1,*) ! to skip first line, with metadata
lmax = 0
do while (.true.)
! read column 1 and 3 here, either write
! that to an array or just loop through each row
end do
99 continue
close (1)
Run Code Online (Sandbox Code Playgroud)
任何解释或示例都会有所帮助.
这很容易。您只需从每行读取 5 个变量,并忽略不再使用的变量。就像是
do i = 1, 100
read(*,*) a(i), b, c(i), d, e
end do
Run Code Online (Sandbox Code Playgroud)
b这将在每次迭代时覆盖、d和中的值e。
顺便说一下,你的线路
99 continue
Run Code Online (Sandbox Code Playgroud)
是多余的;它不用作循环的结束行do,并且您不会从其他任何地方分支到它。如果您从看不见的代码分支到它,您可以将标签附加99到下一行并删除该continue语句。一般来说,continue在现代 Fortran 中是多余的;具体来说,它在您的代码中似乎是多余的。