#MonthOfJulia Day 9: Input/Output
Your code won’t be terribly interesting without ways of getting data in and out. Ways to do that with Julia will be the subject of today’s post.
Direct output to the Julia terminal is done via
println(), where the latter appends a newline to the output.
Terminal input is something that I never do, but it’s certainly possible.
readline() will read keyboard input until the first newline.
Reading and Writing with a Stream
Writing to a file is pretty standard. Below we create a suitable name for a temporary file, open a stream to that file, write some text to the stream and then close it.
println() can also be used in the same way as
write() for sending data to a stream.
STDERR are three predefined constants for standard console streams.
There are various approaches to reading data from files. One of which would be to use code similar to the example above. Another would be to do something like this (I’ve truncated the output because it really is not too interesting after a few lines):
readlines() returns the entire contents of the file as an array, where each element corresponds to a line of content.
readall() would return everything in a single string. A somewhat different approach would be to use
eachline() which creates an iterator allowing you to process each line of the file individually.
Data can be read from a delimited file using
readdlm(), where the delimiter is specified explicitly. For a simple Comma Separated Value (CSV) file it’s more direct to simply use
writcecsv() are used for writing delimited data.
These functions will be essential if you are going to use Julia for data analyses. There is also functionality for reading and writing data in a variety of other formats like xls and xlsx, HDF5 (see embedded media below from JuliaCon2015), Matlab and Numpy data files and WAV audio files.
Julia implements a full range of file manipulation methods (documented here), most of which have names similar to their UNIX counterparts.
A few other details of my dalliance with Julia’s input/output functionality can be found on github.