Message Boards Message Boards

0
|
5377 Views
|
5 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Put Append in Table Format

Posted 11 years ago
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
POSTED BY: Daniele Barducci
5 Replies
Thanks a lot! This looks great :-)
POSTED BY: Daniele Barducci
Posted 11 years ago
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
POSTED BY: David Keith
Posted 11 years ago
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
POSTED BY: David Keith
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!
POSTED BY: Daniele Barducci
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.
POSTED BY: Marco Thiel
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract