wpkzz
wpkzz

Reputation: 899

How to check if file is empty in Julia?

Okey, I want to plot some points that are stored in an array text file (the usual tabular text file) in Julia. I can retrieve the values by a simple data=readdlm("FileInCase01.dat") if the file is not empty. If the file is empty I want data=[], an empty array and an empty plot. The file ALWAYS exists. So isfile is of no use. But sometimes it is empty. If I try to use readdlm on an empty file it returns an error: LoadError: at row 0, column 0 : ArgumentError("number of rows in dims must be > 0, got 0") while loading In[21], in expression starting on line 2 Which suggests that readdlm cannot return an empty array. So I have to check beforehand if the file is empty or not. How is that supposed to be done?

Upvotes: 2

Views: 1460

Answers (1)

mbauman
mbauman

Reputation: 31342

You can check file sizes with filesize:

shell> cat test.csv
#

julia> filesize("test.csv")
2

The file size will be 0 for an empty file. But watch out: even though "test.csv" isn't empty, readdlm will still throw an error since it only contains the comment character:

julia> readdlm("test.csv")
ERROR: at row 0, column 0 : ArgumentError("number of rows in dims must be > 0, got 0")

So @DanGetz's suggestion for a try/catch block is probably the more robust way to handle failures here.

Upvotes: 7

Related Questions