Answers:
以行数组的形式一次将文件读入内存只是对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
为您提供的服务,很少需要自己执行此操作,但是如果需要,功能就在那里。有关逐字符读取文件的更多信息,请参见以下问答:如何使用julia一次读取一个.txt文件的每个字符?