Julia: readdlm fails with leading white space

Viewed 128
using DelimitedFiles
dat = readdlm("tmp.dat", ' ', Float64, '\n')

fails with

ERROR: LoadError: at row 1, column 1 : ErrorException("file entry \"\" cannot be converted to Float64")

when the data file starts with a white space (blank):

 1 2
3 4

When I remove the first space, the Julia program works.

Is there an option to readdlm to ignore leading white space or is there an equally easy alternative?

Edit: Reading an answer below (Thanks!), I realize that I haven't phrased my question precisely. Instead of editing the above and moving the goalpost as a result, I explain my situation. I have ASCII data files, each line of which may or may not start with an unknown number of white spaces. (In addition there may be trailing white spaces.)

Basically what I have in mind is the "usual" ASCII-file read in popular languages like C, Ruby, Fortran, gnuplot . . . In all these languages, leading and trailing white spaces in ASCII-data files are ignored, and inter-word extra spaces are also ignored.

I was surprised readdlm doesn't have such a "mode" of reading. . . .

1 Answers

readdlm supports only skipping entire lines via the skipstart keyword parameter. Hence all you can do is to use seek to skip initial bytes in the stream.

Setup:

open("f.txt","w") do f;println(f," 1 2\n3 4");end

Actual code:

julia> open("f.txt") do f
           seek(f,1)
           readdlm(f, ' ', Float64, '\n')
       end
2×2 Matrix{Float64}:
 1.0  2.0
 3.0  4.0
Related