Julia Language Reading Data from a File


Example

Reading strings or bytes

Files can be opened for reading using the open function, which is often used together with do block syntax:

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

Suppose myfile exists and its contents are

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

Then, this code would produce the following result:

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

Note that eachline is a lazy iterable over the lines of the file. It is preferred to readlines for performance reasons.

Because do block syntax is just syntactic sugar for anonymous functions, we can pass named functions to open too:

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

The functions read and readstring provide convenience methods that will open a file automatically:

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

Reading structured data

Suppose we had a CSV file with the following contents, in a file named file.csv:

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

Then we may use the readcsv function to read this data into a 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      

If the file were instead delimited with tabs, in a file named file.tsv, then the readdlm function can be used instead, with the delim argument set to '\t'. More advanced workloads should use the CSV.jl package.