🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Reading CSV

Reading CSV is loading rows of comma-separated values from a text file. DelimitedFiles is the standard module that reads such files.

Write the file, then read it back

The block writes two rows of numbers first. Reading then returns a matrix of those numbers.

using DelimitedFiles
write("scores.csv", "10,20\n30,40\n")
data = readdlm("scores.csv", ',', Int)
println(size(data))
println(data[1, 2])

A header row names the values

The first row holds names for the values. Reading with header true keeps the names apart from the data.

using DelimitedFiles
write("people.csv", "name,age\nAda,36\nBo,41\n")
data, header = readdlm("people.csv", ',', header=true)
println(header[1])
println(header[2])
println(data[2, 2])

Size counts the rows

The block writes three rows of numbers. Size counts the rows first, then the values in each row.

using DelimitedFiles
write("grades.csv", "5,6\n7,8\n9,10\n")
data = readdlm("grades.csv", ',', Int)
println(size(data, 1))
println(size(data, 2))

Example

using DelimitedFiles
write("students.csv", "name,age\nAda,36\nBo,41\nCy,29\n")
data, header = readdlm("students.csv", ',', header=true)
println(size(data, 1))
println(header[1])
println(data[1, 1])
println(data[3, 2])

Key points

  • DelimitedFiles: This standard module reads text files whose values are separated by commas.
  • Write first: A block writes its CSV file before reading it, so a second run gives the same result.
  • Readdlm: Calling readdlm on a file returns its values as a matrix.
  • Element: Printing one element shows one value from the file.
  • Size: Printing size shows the row count and the value count per row.

In this example, the block writes a small file with a header row and three data rows. It prints the row count, the first header name, the first name, and the last age.

Note

A header row is read separately from the data rows when header is true.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What must a code block do before it reads a CSV file it uses?