【问题标题】:Reading a specific line in Julia阅读 Julia 中的特定行
【发布时间】:2025-11-28 12:40:01
【问题描述】:

由于我是 Julia 的新手,所以我有时会遇到明显的问题。 这次我不知道如何从文件中读取某些数据,即:

...
      stencil: half/bin/3d/newton
      bin: intel
Per MPI rank memory allocation (min/avg/max) = 12.41 | 12.5 | 12.6 Mbytes

Step TotEng PotEng Temp Press Pxx Pyy Pzz Density Lx Ly Lz c_Tr 

  200000    261360.25    261349.16    413.63193    2032.9855    -8486.073    4108.1669    
  200010    261360.45    261349.36    413.53903    22.925126   -29.762605    132.03134   
  200020    261360.25    261349.17    413.46495    20.373081   -30.088775     129.6742   


Loop

我想要的是从“步骤”之后的第三行读取这个文件(从 200010 开始的那个可以是不同的数字 - 我有很多文件在同一个地方但从不同的整数开始)直到程序将到达“循环”。请问你能帮帮我吗?我很累 - 我不知道如何结合 julia 的不同选项来做到这一点......

【问题讨论】:

  • 我已经知道我可以使用“readuntil”命令到达“Loop”,但是我仍然不知道如何在“Step”之后选择第三行或第二行。

标签: file julia readlines


【解决方案1】:

这是一种解决方案。它使用eachline 来遍历行。循环跳过标题和任何空行,并在找到Loop 行时中断。要保留的行在向量中返回。您可能必须根据您拥有的确切文件格式修改标头和/或结束标记的检测。

julia> function f(file)
           result = String[]
           for line in eachline(file)
               if startswith(line, "Step") || isempty(line)
                   continue # skip the header and any empty lines
               elseif startswith(line, "Loop")
                   break # stop reading completely
               end
               
               push!(result, line)
           end
           return result
       end
f (generic function with 2 methods)

julia> f("file.txt")
3-element Array{String,1}:
 "200000 261360.25 261349.16 413.63193 2032.9855 -8486.073 4108.1669"
 "200010 261360.45 261349.36 413.53903 22.925126 -29.762605 132.03134"
 "200020 261360.25 261349.17 413.46495 20.373081 -30.088775 129.6742"

【讨论】:

  • 感谢您的回答。我如何从“200010”行开始阅读,所以“步骤”之后的第 3 行?所以我想我正在阅读文件,当我看到“Step”时,我开始阅读 3 行。
最近更新 更多