Home > OS >  Why Julia is printing junk data to the file?
Why Julia is printing junk data to the file?

Time:12-13

I am new to Julia & this may be a really silly question :) I am running a calculation in Julia & want to output the result to a text file. The main program contains a for loop. After each loop, a single line containing the result for that iteration should be added in the output file(append ). Each line contains multiple values & they should be separated by space.

I checked Julia documentation & syntax seemed quite similar to C . I have tested that with the following code.

using Distributions
f = open("hello.txt","w")
write(f,"Hello again.")
close(f)

numbers=rand(5)

f = open("hello.txt","a")
write(f,numbers)
close(f)

f = open("hello.txt","a")
numbers=rand(5)
print(numbers)

write(f,numbers)

close(f)

Here, I am writing random numbers to a file preceded by a general hello statement. But the output file looks like this though the numbers array contain float numbers (verified in console output).

Hello again.�7D����?L'Uf���?8��f��?���>��?����XX�?�x�m��?Y�]���?�v�S���?x���]�?�zPL�?

Surely, I am doing something silly. This issue is never reported before. I cannot figure out what is wrong here.

And as a good practice, should we need to put close(f)/flush(f) after appending each line(in case of appending data through for loop ) or using close(f) at the end of operation suffice?

Thank you in advance. (Julia 1.6 , Linux 64 bit)

CodePudding user response:

From the documentation of write:

Write the canonical binary representation of a value to the given I/O stream or file.

It looks like you want "text representation" of the numbers, and then you should use print. For Strings, however, the binary representation is the same, so that is why write works with the string.

julia> open("file.txt", "w") do io
           println(io, "Hello")
           println(io, rand(3))
       end

shell> cat file.txt
Hello
[0.11312836652899494, 0.22752036377169926, 0.04622217336925327]

should we need to put close(f)/flush(f) after appending each line(in case of appending data through for loop ) or using close(f) at the end of operation suffice?

The stream is flushed on close.

CodePudding user response:

Another option is to use the Delimited files module with the writedlm function:

using DelimitedFiles

julia> open("hello.txt", "a") do io
            writedlm(io, numbers)
       end

but this seems to be specific for writing numbers from my understanding.

  • Related