How to export a column vector to text file with writedlm function

I want to export a column vector to text file.

using DelimitedFiles
y=[1;2;3.4;5.5;7;8;45.78;0.445;76];
io=open(“x1.txt”,“w”) do io
writedlm(io,y)
end

After the codes is run, I did not get the result I expect. See the screenshot below:

As shown in the screenshot, the variable is a column vector which is showing correctly in Excel (e.g., I use Excel to open the x0.txt Julia generated.). It is showing incorrectly in windows notepad program.
What should I do to make the txt file look correct?

If I understand correctly, you simply want to write a vector of numbers to a text file such that each number is followed by “\n”. If so:

io = open("test.txt", "w") do io
  for x in y
    println(io, x)
  end
end

would seem easiest. Or do I misunderstand what you are trying to do?

BTW, one would usually separate elements in a vector with “,” rather than “;”.

3 Likes

I tried your suggested code. It gives the same results as mine.
Please see the screenshot. I want the txt file to display the results in a column instead of a row.
Specifically, it should have a new line command for each row.
The screenshot show the txt file is a column when I use Excel to open it.
But it is a row in the txt file.

Notepad is the “used napkin” of note-taking programs. Please use a real text editor and you will see that it works just fine!

1 Like

What version of Windows do you have? Prior to Windows 10, Notepad did not support \n Unix-style line endings, which is what Julia produces by default.

I would suggest getting a better text editor. vscode is free and fast, for example.

3 Likes

Thanks. I installed VS Code and it shows the result I expect.

For a 2D array, this code does not produce the output I expect:

julia> y=rand(9,4)
9×4 Array{Float64,2}:
 0.555096   0.00464277  0.0304166  0.843892
 0.678299   0.314659    0.283303   0.985769
 0.485882   0.576767    0.295104   0.669978
 0.327327   0.819604    0.134858   0.820752
 0.0562406  0.270076    0.346032   0.470565
 0.109073   0.668393    0.548311   0.217529
 0.244507   0.0839197   0.148862   0.0777072
 0.0740043  0.544063    0.608664   0.779534
 0.500565   0.699411    0.964454   0.164854

I want to print the above 2D array into txt file with the following code:

y=rand(9,4);
s=size(y);
io=open("a4.txt","w") do io
    for i=1:s[1]
        for j=1:s[2]
            if j < s[2]
                println(io, y[i,j],"\t")
            else
                println(io, y[i,j],"\n")
            end
        end
    end
end

Then I got this output in VS code. How can get this 2D array output correctly?

Use print, not println; the latter appends a newline. Or just use writedlm

Thanks a lot for the help! Very appreciate it.