Search code examples
iojulia

Read a column file in julia


I would not like to pickaxe a lot in the language just to read a file with numerical data arranged by columns. Is there an easy way to do this now in julia 1.1? Surprisingly this simple task is not on the manual. In python one would do something like this:

def read2col(filename, length):
    data = []
    for line in open(filename,'r'):
        for word in line.split():
            data.append(word)

data = np.reshape(data,(length,2))
data = np.asarray(data, dtype=np.float64)
return data

Solution

  • (untested)

    function read2col(filename, len)
        asfloat64(s) = try x = parse(Float64, s); return x catch; return missing; end
        data = []
        for word in split(read(filename, String), r"\s+")
            push!(data, word)
        end
        data = reshape(data,(len, 2))
        data = asfloat64.(data)
        return data
    end
    

    or even

    asfloat64(s) = try x = parse(Float64, s); return x catch; return missing; end
    read2col(fname, len) = asfloat64.(reshape(split(read(fname, String), r"\s+"), (len, 2)))