Printing an array into a text file

Hello,
I have an array that I’d like to print into a text file.

notes = ["C4", "D4", "E4", "F4"]
outfile = "notes.txt"
f = open(outfile, "w")

for i in notes
	println(f, notes[i])
end

For some reason, my ‘for loop’ is complaining and saying “ArgumentError: invalid index: C4”

Thanks!
Nakul

Welcome!

First, check out how to quote your code with backticks to maintain readability.

The issue is that your iterator for i in notes means that each i is the element of notes. So what you want is

for i in notes # or for note in notes
println(f, i)
end

Or if you want to iterate through the indices of notes, you can use the function eachindex

for i in eachindex(notes)
println(f, notes[i])
end
2 Likes

Thank you! For some reason the array isn’t getting stored into the text file. Any idea why?

are you closing the text file when you are done?

1 Like

I do close it but it is always empty, even when I open it.

If you could provide a complete minimum working example it would help us debug your problem a bit more

I finally understood what you meant by closing the file. I thought you meant in my editor haha, but close(f) worked for me. Thanks so much. That was a close call…

You can use a do-block to conveniently ensure that your file gets closed when you’re done writing to it:

notes = ["C4", "D4", "E4", "F4"]
outfile = "notes.txt"
open(outfile, "w") do f
  for i in notes
    println(f, i)
  end
end # the file f is automatically closed after this block finishes

To learn about why this works, check out the manual: https://docs.julialang.org/en/v1/manual/functions/#Do-Block-Syntax-for-Function-Arguments-1

4 Likes