Prithvi Thakur
Prithvi Thakur

Reputation: 273

Open file with formatted variable name in Julia

I have a list of files numbered gll_01.tab, gll_02.tab, ...., gll_20.tab in a subdirectory of my parent directory. These files are tabular data files.

I want to open/read files with user-specified input.

I can do:

a = 3
open("directory/gll_0$a.tab")

But using this approach, I would have to define two separate variable names for (01 to 09) and for (10 to 18). How can I use variables or strings with name 02, 03, ..., etc?

In python, I can have an equivalent command:

a = 4
g = '{:02d}'.format(a)
f = open('directory/gll_%s.tab' %g)

Is there an equivalent string formatting command in Julia?

Upvotes: 3

Views: 890

Answers (2)

niczky12
niczky12

Reputation: 5073

Another option is to use @sprintf, docs are here. With that you can use %02d as a formatting option that would pad a digit d to length 2 with 0s preceding it:

julia> using Printf # this is in the standard library
julia> @sprintf("directory/gll_%02d.tab", 1)
"directory/gll_01.tab"

You can use this in your open statements too. Here they are in action:

julia> for i in 5:10
           println("$i file is: $(@sprintf("directory/gll_%02d.tab",i))")
       end
5 file is: directory/gll_05.tab
6 file is: directory/gll_06.tab
7 file is: directory/gll_07.tab
8 file is: directory/gll_08.tab
9 file is: directory/gll_09.tab
10 file is: directory/gll_10.tab

Upvotes: 2

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69939

A simple answer in this case would be to use lpad:

a = 3
open("directory/gll_$(lpad(a,2,"0")).tab")

If you need more fancy formatting you can use e.g. https://github.com/JuliaIO/Formatting.jl, in this case this would be:

using Formatting
a = 3
open("directory/gll_$(fmt("0>2", a)).tab")

Upvotes: 3

Related Questions