Put Append in Table Format

Hi, I am trying to export on the fly some tables within a loop, doing something like

For[i = 1, i <= 3, i++, PutAppend[{{i, i^2}}, “tmp.dat”] ]

and it indeed works, despite the fact that the output file is something like

{{1, 1}}{{2, 4}}{{3, 9}}

why I would like to have something like

1 1
2 4
3 9

that could be achieved with Export for example. Is there a way to do this? I tried with and option “Table” in PutAppend, but it does not work.

Thanks

Daniele

Hi Daniele,
would something like that work?

For[i = 1, i <= 3, i++, PutAppend["{" <> ToString[i] <> "," <> ToString[i^2] <> "}", "~/Desktop/tmp.dat"]]

Reading the data with

data = Flatten[ToExpression[Import["~/Desktop/tmp.dat"]], 1]

gives a result close to what you want:

data // TableForm

(*

1    1
2    4
3    9

*)

It’s not very elegant though…

M.

Actually it works, but the fact is that my output file in the form

1 2
2 4
3 9

has to been used as an input for another program and I need it in this form. Actually I could use your method and then write a script to convert in the format I want, but I was hoping to have something more involved, but maybe with PutAppend is not possible.

Thanks a lot!

How about this:

(* function to write two numbers to a stream followed by newline *)
output[{n_, m_}, stream_] := WriteString[stream, n, " ", m, "\n"]

(* filename *)
file = "temp.txt";

(* open a stream called out, which overwrites it *)
out = OpenWrite["temp.txt"];

(* write several pairs *)
output[{3, 4}, out];
output[{5, 6}, out];
output[{7, 8}, out];

(* close the stream *)
Close[file];

(* print the file *)
FilePrint["temp.txt"]

3 4
5 6
7 8

Or, to use it inside your For loop:

(* function to write two numbers to a stream followed by newline *)
output[{n_, m_}, stream_] := WriteString[stream, n, " ", m, "\n"]

(* filename *)
file = "temp.txt";

(* open a stream called out, which overwrites it *)
out = OpenWrite["temp.txt"];

(* write several pairs *)
For[i = 1, i <= 3, i++, output[{i, i^2}, out]]

(* close the stream *)
Close[file];

(* print the file *)
FilePrint["temp.txt"]

1 1
2 4
3 9

Thanks a lot! This looks great :slight_smile: