5
$\begingroup$

When u write a list into a file, like in the example below

list={{1,2},{2,1},{1,3},{4,2},{4,1}};
myfile=OpenWrite["C:\\myfile.txt"];
Table[Write[myfile,list[[i]]],{i,1,Length[list]}];

The output u get is:

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

The output I wish to have is:

1 2 2 1 1 3 4 2 4 1

I cannot export the whole list as in my work I need to print things on the go, so the structure of the write command need to be the same unless u have an alternative

$\endgroup$

marked as duplicate by Öskå, Szabolcs, user9660, Yves Klett, J. M. will be back soon Jul 7 '16 at 0:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    $\begingroup$ You might use Export to write the file out in CSV format. $\endgroup$ – m_goldberg Jul 4 '16 at 16:33
  • $\begingroup$ @m_goldberg I would prefer to keep this structure, in my code there is a function that gives output to a vector with length 2 and the list length is very very long, so to save time I wish to print to the file on the go $\endgroup$ – jarhead Jul 4 '16 at 16:34
  • $\begingroup$ Can you be explicit in terms of the output you need? Is it only for a list of precisely these dimensions or does this need to be more flexible? (Either way, please add all additional information as edits to the post rather than comments under it as those can be deleted at any time.) $\endgroup$ – Emilio Pisanty Jul 4 '16 at 16:41
  • $\begingroup$ @EmilioPisanty, edited. $\endgroup$ – jarhead Jul 4 '16 at 16:45
6
$\begingroup$

Write writes expressions out in InputForm, so you really need to use WriteString

With[{delimiter = " "},
  helper[strm_, {x_, y_}] := WriteString[strm, x, delimiter, y, delimiter]]

With[{
    data = {{1, 2}, {2, 1}, {1, 3}, {4, 2}, {4, 1}},
    file = FileNameJoin[{$HomeDirectory, "Desktop", "data.txt"}]},
  Module[{out},
    out = OpenWrite[file]; 
    AbortProtect[helper[out, #] & /@ data; Close[out]]]]

FilePrint[FileNameJoin[{$HomeDirectory, "Desktop", "data.txt"}]]

1 2 2 1 1 3 4 2 4 1

$\endgroup$
  • $\begingroup$ Actually Write uses FormatType of the specified output channel which for OpenWrite by default has FormatType -> InputForm. $\endgroup$ – Alexey Popkov Jul 4 '16 at 18:01
  • $\begingroup$ @AlexeyPopkov. Good point. I edited the answer to conform. $\endgroup$ – m_goldberg Jul 4 '16 at 18:08

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