逐行读取文本文件,但仅读取特定列 [英] Read text file line by line but only specific columns

查看:67
本文介绍了逐行读取文本文件,但仅读取特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何在跳过某些特定列的同时逐行读取特定文件?

How do we read a specific file line by line while skipping some columns in it?

例如,我有一个包含数据的文本文件,该文件分为5列,但我只需要读出其中的两列,它们可以是前两列或任何其他随机组合(我的意思是,需要一种解决方案可以与任何列组合(例如仅第一列和第三列)一起使用.

For example, I have a text file which has data, sorted out in 5 columns, but I need to read only two columns out of it, they can be first two or any other random combination (I mean, need a solution which would work with any combination of columns like first and third only).

编写类似这样的代码

        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)

任何解释或示例都会有很大帮助.

Any explanation or example would help a lot.

推荐答案

这非常容易.您只需从每一行中读取5个变量,而忽略不再使用的变量.像

This is very easy. You simply read 5 variables from each line and ignore the ones you have no further use for. Something like

do i = 1, 100
    read(*,*) a(i), b, c(i), d, e
end do

这将在每次迭代时覆盖 b d e 中的值.

This will overwrite the values in b, d, and e at every iteration.

顺便说一句,你的台词

99 continue

是多余的;它不会用作 do 循环的结束线,并且您不会从其他任何地方分支到它.如果您是从看不见的代码分支到它,则只需将标签 99 附加到下一行并删除 continue 语句.通常, continue 在现代Fortran中是多余的.具体来说,这似乎在您的代码中是多余的.

is redundant; it's not used as the closing line for the do loop and you're not branching to it from anywhere else. If you are branching to it from unseen code you could just attach the label 99 to the next line and delete the continue statement. Generally, continue is redundant in modern Fortran; specifically it seems redundant in your code.

这篇关于逐行读取文本文件,但仅读取特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆