Creating Fixed Width Output Files

I am unsatisfied with the discussion here, so am opening a new thread to find a solution to this.

In Python, it is quite simple to save a data frame or dictionary with fixed width columns as a .dat file. This usability does not seem to exist in Julia. What is the simplest method possibly (ideally avoiding some obscure package) to construct variable size delimiters for saving human readable .dat files?

To give a minimal working example of most of what I am hoping for

using DelimitedFiles, DataFrames

inputfile = "/home/local_directory_example/inputfile.json"
outputfile = "/home/local_directory_example/output_directory/"
# some dictionary that will get created
d = Dict("ALPHA TEST" => [5.240,1.2340,23.445625633676,4.30,5.2340], "B" => [4.235,3.0,2.245,5.245,1.245])
df = DataFrame(d)
fobj = open(inputfile ,"r")
input_file_contents = read(fobj, String)
fobj2=open(filename*"_test.dat", "w")
write(fobj2, input_file_contents)
writedlm(fobj2,Iterators.flatten(([names(df)], eachrow(df))))

This creates a header in my .dat file with my input file and saves the output data but the formatting is unsightly.

1 Like

That’s neither a minimal working example nor is it running (inputfile.json is missing). A good MWE can be copy-pasted into a fresh Julia session and ran without errors (unless the error is part of the example :wink: ).

I am wondering how your “quite simple” Python implementation looks like, I am pretty sure you can translate it more or less one-to-one to Julia.

Anyways, maybe this is what you are looking for (no “obscure” packages, whatever that means):

using Printf
using DataFrames

n = 10

df = DataFrame(
    Dict("A" => rand(n), "B" => rand(n))

entry_fmt = "%9.3f"

open("out.dat", "w") do fobj
    row_fmt = Printf.Format(entry_fmt^ncol(df) * "\n")
    for row ∈ eachrow(df)
        Printf.format(fobj, row_fmt, values(row)...)
$ cat out.dat
    0.944    0.390
    0.811    0.148
    0.542    0.832
    0.874    0.840
    0.026    0.467
    0.611    0.962
    0.745    0.851
    0.358    0.604
    0.179    0.921
    0.298    0.062

perhpas this function of InMemorydataset pkg, it suits you