How to do format write correctly?

I am sorry another stupid question, I read the IO part of the Julia documents I/O and Network · The Julia Language, but I am still too stupid to do the following simply thing.

For example, the short illustration code below is what I wrote,

LL = [-1129.252,-648.5315,-553.8973,-461.6156,-356.7228,-265.5437,-170.7289,-86.96198,-40.47620,-23.48844,-20.80410]
io = open("myfile.txt", "w")
for i in 1:length(LL)
    write(io, "$(i)  $(LL[i]) \n")
end
close(io)

The output is like,

1  -1129.252 
2  -648.5315 
3  -553.8973 
4  -461.6156 
5  -356.7228 
6  -265.5437 
7  -170.7289 
8  -86.96198 
9  -40.4762 
10  -23.48844 
11  -20.8041

You see the line 9 and 10, the values are not very well aligned.

In Fortran, i can do format write things like,

do iter = 1,10
     write(11,'(i10,1x,g15.7)') iter, Loglike(iter)
enddo

the format (i10,1x,g15.7) can make the values well aligned,

     0   -1129.252    
     1   -648.5315    
     2   -553.8973    
     3   -461.6156    
     4   -356.7228    
     5   -265.5437    
     6   -170.7289    
     7   -86.96198    
     8   -40.47620    
     9   -23.48844    
    10   -20.80410

I know in Julia it can use the same printf grammar like C. However, I tried some printf grammar in the write, but it does not work.

Does anyone knows how to achieve similar effects as the Fortran results?

Thank you very much in advance!

https://docs.julialang.org/en/v1/stdlib/Printf/

Is what you’re looking for I think

https://docs.julialang.org/en/v1/stdlib/Printf/

Is what you’re looking for I think

Things like

@printf(io, “%10d %0.f \n”, i, LL[i])

did the trick.

Thanks. Sorry I did not notice that printf can serve as write.

1 Like