I am using the following code to print some data to an external file :

file = OpenAppend["abc.dat"]

Do[Export[file, {u, ClassicalFish[1, 2, 10^-5, 100, u, 2, 40]}]; 
 WriteString[file, "\n"], {u, 0.0003, 0.99, 0.0001}]


This writes the data to the file but there is a new line after each u and each ClassicalFish[1, 2, 10^-5, 100, u, 2, 40]}] in abc.dat. If I don't include WriteString[file, "\n"] then everything is printed one after the other.

Please provide some solution for this. I would like to print a "\t" between each u and ClassicalFish[1, 2, 10^-5, 100, u, 2, 40]}] pair and after that a "\n".


Avoid procedural loops in Matehmatica (Do, For, While etc). Instead, generate your dataset with Table, then export it all in one go:

yourData = Table[
              {u, ClassicalFish[1, 2, 10^-5, 100, u, 2, 40]}, 
              {u, 0.0003, 0.99, 0.0001}

Export["abc.dat", yourData, "TSV"]

Using the "TSV" export format will give you tab-separated values, one pair of values per line.

Alternative method that exports each result as they are being created:

file = OpenAppend["abc.dat"];
  Export[file, {{u, ClassicalFish[1, 2, 10^-5, 100, u, 2, 40]}}, "TSV"],
  {u, 0.0003, 0.99, 0.1}
  • $\begingroup$ Actually, I want to print data to file for each run because my code can take even upto 40 hours or so and there is a possibility that I may have to stop the code before full evaluation. $\endgroup$
    – Nitin
    Apr 22 '20 at 17:54
  • $\begingroup$ @Nitin Got it. See the alternative method I added. $\endgroup$
    – MarcoB
    Apr 22 '20 at 18:06
  • $\begingroup$ This almost did it, except that there is no newline after ClassicalFish[1, 2, 10^-5, 100, u, 2, 40] is printed. $\endgroup$
    – Nitin
    Apr 22 '20 at 18:16
  • $\begingroup$ The following does it Table[Export[ file, {{u, ClassicalFish[1, 2, 10^-5, 100, u, 2, 40], "\n"}}, "TSV"], {u, 0.0003, 0.99, 0.0001}] . If you can add this or something similar then I can happily accept this as an answer (since the question is specifically about newline). If possible can you also explain why this works? Thanks a lot :) $\endgroup$
    – Nitin
    Apr 22 '20 at 18:19
  • $\begingroup$ @Nitin, just to clarify, you want TWO new lines after each data entry? i.e. you want an empty line in between each entry? Of course I do not have the definition of ClassicalFish, so I do not know what it returns exactly, but if I replace it with any other numerical function (e.g. Sin[u]), then each entry is already separated into its own line. Is it different on your system? $\endgroup$
    – MarcoB
    Apr 23 '20 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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