从文件中读取数据

读取字符串或字节

可以使用 open 函数打开文件进行读取,open 函数通常与 do 块语法一起使用 :

open("myfile") do f
    for (i, line) in enumerate(eachline(f))
        print("Line $i: $line")
    end
end

假设 myfile 存在且其内容为

What's in a name? That which we call a rose
By any other name would smell as sweet.

然后,此代码将产生以下结果:

Line 1: What's in a name? That which we call a rose
Line 2: By any other name would smell as sweet.

请注意,eachline 是文件行上的一个可迭代迭代 。出于性能原因,优选 readlines

因为 do 块语法只是匿名函数的语法糖,所以我们也可以将命名函数传递给 open

julia> open(readstring, "myfile")
"What's in a name? That which we call a rose\nBy any other name would smell as sweet.\n"

julia> open(read, "myfile")
84-element Array{UInt8,1}:
 0x57
 0x68
 0x61
 0x74
 0x27
 0x73
 0x20
 0x69
 0x6e
 0x20
    ⋮
 0x73
 0x20
 0x73
 0x77
 0x65
 0x65
 0x74
 0x2e
 0x0a

函数 readreadstring 提供了自动打开文件的便捷方法:

julia> readstring("myfile")
"What's in a name? That which we call a rose\nBy any other name would smell as sweet.\n"

阅读结构化数据

假设我们在名为 file.csv 的文件中有一个包含以下内容的 CSV 文件

Make,Model,Price
Foo,2015A,8000
Foo,2015B,14000
Foo,2016A,10000
Foo,2016B,16000
Bar,2016Q,20000

然后我们可以使用 readcsv 函数将这些数据读入 Matrix

julia> readcsv("file.csv")
6×3 Array{Any,2}:
 "Make"  "Model"       "Price"
 "Foo"   "2015A"   8000       
 "Foo"   "2015B"  14000       
 "Foo"   "2016A"  10000       
 "Foo"   "2016B"  16000       
 "Bar"   "2016Q"  20000      

如果文件用制表符分隔,在名为 file.tsv 的文件中,则可以使用 readdlm 函数,将 delim 参数设置为'\t'。更高级的工作负载应使用 CSV.jl