2
$\begingroup$

I can't find proper documentation on this but basically I want to

  1. open a .txt file to write in Mathematica in a defined path.
  2. then I want to write to that file line by line probably
  3. close the file

Im looking for the Mathematica equivalent of what in C would be fopen -> fprintf -> fclose

Thank you.

$\endgroup$
1

1 Answer 1

4
$\begingroup$

There is no printf in Mathematica. But to write to a file, just use WriteString. Just make sure to convert everything to string, including any Mathematica expressions, and make sure to use InputForm, to avoid 2D. Also need to add an explicit "\n" at end of each line to get CR.

If you want to append, do not delete the file as below, but use OpenAppend.

SetDirectory[NotebookDirectory[]]
fileName = FileNameJoin[{Directory[], "test.txt"}]
If[FileExistsQ[fileName],DeleteFile[fileName]];
file=OpenWrite[fileName,PageWidth->Infinity];
Do[
   WriteString[file,ToString@n<>"\n"];
   If[n == 5, WriteString[file, ToString[InputForm@Sin[x/Pi]] <> "\n"]]
   ,
   {n,1,10}
];
Close[file]

Here is the content of the file

1
2
3
4
5
Sin[x/Pi]
6
7
8
9
10
$\endgroup$
3
  • $\begingroup$ Perfect, thank you, this was what I was looking for $\endgroup$ Jun 13, 2023 at 23:14
  • $\begingroup$ Why WriteString and not WriteLine? $\endgroup$ Jun 14, 2023 at 10:10
  • $\begingroup$ @infinitezero WriteLine is fine. I happen to prefer WriteString so I can control when to add "\n", as I generate lots of Latex and sometimes I want to write small string in middle of building the full Latex which is not fully done yet, and do not want to insert CR yet. So WriteString gives me more control that way. But if someone does not need this control, WriteLine is fine solution. $\endgroup$
    – Nasser
    Jun 15, 2023 at 5:16

Your Answer

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

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