從檔案中讀取資料
讀取字串或位元組
可以使用 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
函式 read 和 readstring 提供了自動開啟檔案的便捷方法:
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 包 。