Exporting/printing an array of dictionaries to external text file

Hi,

I’m trying to export a Julia array (of dictionaries, among some oddities) to a text file to share with a colleague.

The array in question looks something like this, but about 70k entries:

 Dict{String, Any}("tem" => false, "cl" => "B")
 nothing
 Dict{String, Any}("tem" => true, "cl" => "AS")
 Dict{String, Any}("tem" => false, "cl" => "CR")
 Dict{String, Any}("tem" => false, "cl" => "EB")

So far I tried following the 2018 solution posted on a similar topic:

f = open("demo.txt", "w")

for i in eachindex(slice_array)
println(f, slice_array[i])
end

And a to-the-letter version:

outfile="demo.txt"
f = open(outfile,"w")

for i in eachindex(slice_array)
println(f, slice_array[i])
end

While both approaches do create a ‘demo.txt’ output file, the content of the file itself is empty. Testing the loop portion without the f io does seem to print all the lines in the REPL without issues.

What could I be doing wrong?

Any advice would be appreciated. Thank you!

Looks like you just need to close the file after the writes.

It’s usually preferred to use the do block form of the open function which ensures this will happen automatically:

outfile="demo.txt"
open(outfile, "w") do f
  for i in eachindex(slice_array)
    println(f, slice_array[i])
  end
end
1 Like

Yes, that fixed everything right up - now I feel silly.

Thank you for the help!

1 Like

I would really consider using JSON here.

  • JSON.jl
  • JSON3.jl
2 Likes

Thank you for the suggestion!

The original entry is produced using JSON.jl - I’m trying to make one mess of a file (compiled by unrelated undergrads from across dozens of unis) with lots of sub-sub-branches and occasional non-formatted personal comments & gibberish I don’t understand thrown in for a good measure.

I do have additional questions on piecing this thing together, but will write them on a separate post.