Julia equivalent of Python (numpy.savetxt) and Matlab (save) commands?

What is the Julia equivalent of the following Python and MATLAB codes?
I’m looking for identical formatting in the output.

After searching the documentation (e.g. JLD, CSV, DataFrames), I have not found a satisfactory answer, hence I’m asking here.

(MATLAB) Input:

p = [1 2]
q = [3 4]
save pqfile.txt p q -ascii -double

(MATLAB) Output:

1.0000000000000000e+00   2.0000000000000000e+00
3.0000000000000000e+00   4.0000000000000000e+00

(Python) Input:

import numpy as np
p = np.array([1, 2])
q = np.array([3, 4])
np.savetxt("pqfile.txt", [p, q], fmt='%.16e')

(Python) Output:

1.0000000000000000e+00   2.0000000000000000e+00
3.0000000000000000e+00   4.0000000000000000e+00

Would CSV work? Check out DelimitedFiles.

The easiest way is to use writedlm, but that won’t give you the exact same formatting:

using DelimitedFiles
p = [1, 2]
q = [3, 4]
writedlm("pqfile.txt", (p, q), "   ")

# Output:
# 1   2
# 3   4

If you want more control over the formatting you can write the file manually using the @printf macro and iterating over the arrays.

1 Like

Adding to the above questions, also check Formatting.jl if you are used to Python syntax.

I’m looking into Formatting.jl - does this package give only string output, or can it be used to write to files?

You can write any string to a file using
https://docs.julialang.org/en/v1/base/io-network/#Base.open