1
$\begingroup$

I have some problems exporting Table data into ASCII files preserving column alignment.

By example (under Mathematica v11.2 + Linux):

I generate a random table with 2 columns

t = Table[StringJoin[RandomChoice[CharacterRange["A", "Z"], RandomInteger[{1,10}]]], 10, 2];
UOTKRPUOVS   PZFON
WQSMI        FVAGV
SGOZQJP      KYWTGIBGF
B            QEKUEFN
EKPU         WVIKS
CHXJBPGXA    BAMYNNG
FZFXXWZ      TQUYN
A            K
ICZFK        MDLKDKIGTD
NLXH         WVAWTL

I export it into a Text file with this command:

Export["test.txt", t, "Table"]

However if I look the exported file (from terminal):

cat test.txt

I get:

UOTKRPUOVS    PZFON
WQSMI FVAGV
SGOZQJP   KYWTGIBGF
B QEKUEFN
EKPU  WVIKS
CHXJBPGXA BAMYNNG
FZFXXWZ   TQUYN
A K
ICZFK MDLKDKIGTD
NLXH  WVAWTL

-> column alignment is completely lost.

Fix?:

The only way I have found so far to fix this issue is to export the table using:

Export["test.txt", StringReplace[ToString[Grid[t]], "\n\n" -> "\n"], "Text"]

Now,

cat test.txt

gives me back the right formatting:

UOTKRPUOVS   PZFON
WQSMI        FVAGV
SGOZQJP      KYWTGIBGF
B            QEKUEFN
EKPU         WVIKS
CHXJBPGXA    BAMYNNG
FZFXXWZ      TQUYN
A            K
ICZFK        MDLKDKIGTD
NLXH         W

This works but that seems a very awkward solution for such a basic problem...

Any better idea?


Note: maybe the StringReplace[..., "\n\n" -> "\n"] step is useless under Windows, but I had not the opportunity to check that.

$\endgroup$

2 Answers 2

3
$\begingroup$

You can do :

t = Table[StringJoin[RandomChoice[CharacterRange["A", "Z"], RandomInteger[{1, 10}]]],10, 2];  

ToString@Format[TableForm[t, TableSpacing -> {0, 1}], OutputForm]

enter image description here

Then export the string.

Surpisingly it works fine too with arbitrary ragged nested list :

    ToString@Format[
  TableForm[{12, s, {2, 6777}, {6, 8, {7, 8}}}, 
   TableSpacing -> {0, 1}, TableAlignments -> {Left, Top, Left}], 
  OutputForm] 

enter image description here

This functionality of Mathematica is very old. (Mma 2 at least). It may be supersed by something more modern.

EDIT

It is also possible to write directly in a file, like this :

st = OpenWrite["test.txt", FormatType ->  OutputForm];
Write[st, TableForm[t, TableSpacing -> {0,1}]];
Close[st];
Import["test.txt"]

(* same output as above *)

$\endgroup$
3
  • $\begingroup$ (+1) Using TableForm for this request is kind of no-brainer, but it did not occur to me! (And I am a fan of TableForm.) $\endgroup$ Nov 26, 2020 at 13:51
  • $\begingroup$ @AntonAntonov I'm a fan of TableForm too. In the same spirit as your "gridTableForm", I have created my "flatTableForm" in 2019. The idea was to flatten an arbitrary depth ragged and unbalanced array in a 2 dimensionnal array without lost of information. The code and some demos are [here].(chat.stackexchange.com/transcript/message/51392005#51392005). $\endgroup$
    – andre314
    Nov 26, 2020 at 17:33
  • $\begingroup$ Cool ! Please, consider submitting a Wolfram Function Repository function. $\endgroup$ Nov 28, 2020 at 1:00
1
$\begingroup$

Slight modifications of the code in the question:

t = Table[StringJoin[RandomChoice[CharacterRange["A", "Z"], RandomInteger[{1, 10}]]], 10, 4];
Export[FileNameJoin[{NotebookDirectory[], "test.txt"}], t, "Table"];
RunProcess[{"cat", FileNameJoin[{NotebookDirectory[], "test.txt"}]}]["StandardOutput"]

The following export code might be too ad hoc but works:

Clear[AddSpaces]
AddSpaces[col : {_String ..}] :=
  Block[{m = Max@Map[StringLength, col]},
   Map[StringJoin[#, StringJoin @@ Table[" ", m - StringLength[#]]] &,
     col]
   ];

t2 = Transpose[Map[AddSpaces, Transpose[t]]];
Export[FileNameJoin[{NotebookDirectory[], "test2.txt"}], t2, "Table"];

RunProcess[{"cat" , FileNameJoin[{NotebookDirectory[], "test2.txt"}]}]["StandardOutput"]

enter image description here

(I strongly suspect there is a solution using the options of Export.)

$\endgroup$
2
  • $\begingroup$ Thanks. Yes, I was also hoping to find a solution with Export... But I searched for some time without success.... $\endgroup$ Nov 25, 2020 at 13:54
  • 1
    $\begingroup$ @PicaudVincent -- Sure, good luck! $\endgroup$ Nov 25, 2020 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.