【问题标题】:How to read a file line by line in Julia?如何在 Julia 中逐行读取文件?
【发布时间】:2020-01-29 20:32:14
【问题描述】:

如何打开文本文件并逐行读取?我对两种不同的情况感兴趣:

  1. 一次获取数组中的所有行。
  2. 一次处理每一行。

对于第二种情况,我不想一次将所有行都保存在内存中。

【问题讨论】:

    标签: file-io julia


    【解决方案1】:

    将文件作为行数组一次全部读入内存只是对readlines函数的调用:

    julia> words = readlines("/usr/share/dict/words")
    235886-element Array{String,1}:
     "A"
     "a"
     "aa"
     ⋮
     "zythum"
     "Zyzomys"
     "Zyzzogeton"
    

    默认情况下这会丢弃换行符,但如果你想保留它们,你可以传递关键字参数keep=true

    julia> words = readlines("/usr/share/dict/words", keep=true)
    235886-element Array{String,1}:
     "A\n"
     "a\n"
     "aa\n"
     ⋮
     "zythum\n"
     "Zyzomys\n"
     "Zyzzogeton\n"
    

    如果你有一个已经打开的文件对象,你也可以将它传递给readlines 函数:

    julia> open("/usr/share/dict/words") do io
               readline(io) # throw out the first line
               readlines(io)
           end
    235885-element Array{String,1}:
     "a"
     "aa"
     "aal"
     ⋮
     "zythum"
     "Zyzomys"
     "Zyzzogeton"
    

    这演示了readline 函数,该函数从打开的 I/O 对象中读取一行,或者在给定文件名时打开文件并从中读取第一行:

    julia> readline("/usr/share/dict/words")
    "A"
    

    如果您不想一次加载所有文件内容(或者如果您正在处理来自网络套接字的流数据),那么您可以使用eachline 函数获取生成第一行的迭代器一次:

    julia> for word in eachline("/usr/share/dict/words")
               if length(word) >= 24
                   println(word)
               end
           end
    formaldehydesulphoxylate
    pathologicopsychological
    scientificophilosophical
    tetraiodophenolphthalein
    thyroparathyroidectomize
    

    eachline 函数也可以像readlines 一样被赋予一个打开的文件句柄来读取行。您还可以通过打开文件并反复调用 readline 来“滚动您自己的”迭代器:

    julia> open("/usr/share/dict/words") do io
               while !eof(io)
                   word = readline(io)
                   if length(word) >= 24
                       println(word)
                   end
               end
           end
    formaldehydesulphoxylate
    pathologicopsychological
    scientificophilosophical
    tetraiodophenolphthalein
    thyroparathyroidectomize
    

    这相当于eachline 为您做的事情,很少需要自己做,但如果您需要,能力就在那里。有关逐字符读取文件的更多信息,请参阅此问答:How do we use julia to read through each character of a .txt file, one at a time?

    【讨论】:

      猜你喜欢
      • 2011-11-02
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2015-05-21
      相关资源
      最近更新 更多