user2820579
user2820579

Reputation: 3451

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

Upvotes: 1

Views: 1489

Answers (3)

Steven Siew
Steven Siew

Reputation: 873

The laziest way to do it is to use CSV.jl

using CSV
for row in CSV.File("file.txt",delim=' ',ignorerepeated=true)
  println("a=$(row.a), b=$(row.b), c=$(row.c)")
end

delim=',': a Char or String that indicates how columns are delimited in a file; if no argument is provided, parsing will try to detect the most consistent delimiter on the first 10 rows of the file

Upvotes: 1

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42194

There is already an inbuilt function in Julia that does exactly that:

using DelimitedFiles
reshape(readdlm("myfilename.txt"),:,2)

Let's give it a spin:

shell> more file.txt
1 2 3
4 5 6
7 8 9
10 11 12

julia>  reshape(readdlm("file.txt"),:,2)
6×2 Array{Float64,2}:
  1.0   8.0
  4.0  11.0
  7.0   3.0
 10.0   6.0
  2.0   9.0
  5.0  12.0

or if you want a different ordering just transpose with '

julia>  reshape(readdlm("file.txt")',:,2)
6×2 reshape(::LinearAlgebra.Adjoint{Float64,Array{Float64,2}}, 6, 2) with eltype Float64:
 1.0   7.0
 2.0   8.0
 3.0   9.0
 4.0  10.0
 5.0  11.0
 6.0  12.0

Upvotes: 4

Bill
Bill

Reputation: 6086

(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)))

Upvotes: 1

Related Questions