I know that new line is classically made by "\n".

I want to make a string with lines of data and then export it into a file:

outString = StringJoin["First Line \nSecond Line"]
Put[outString, NotebookDirectory[] <> "testOut.txt"]

The first line, make a decent output in the Mathematica itself:

"First Line 
Second Line"

But in the testOut.txt file , it is :

"First Line \nSecond Line"

Note that it even includes the quotation marks and both in the same line ! What is the solution for that ?


1 Answer 1

Put[OutputForm[outString], "testOut.txt"]

enter image description here

compare with

Put[outString, "testOut0.txt"]

enter image description here

Alternatively, you can use Export:

Export["testOut2.txt", outString]
(* or Export["testOut2.txt", outString, "Text"] *)

or, WriteString (thanks: Mr.Wizard)

strm = OpenWrite["testOut2.txt"];
WriteString[strm, outString]

to get the same result:

enter image description here

  • 1
    $\begingroup$ Consider also mentioning WriteString +1 $\endgroup$
    – Mr.Wizard
    Apr 23, 2015 at 23:31
  • $\begingroup$ Thanks @Mr.W, added WriteStream. $\endgroup$
    – kglr
    Apr 23, 2015 at 23:46
  • $\begingroup$ Great ! Thank you $\endgroup$
    – Aug
    Apr 23, 2015 at 23:59
  • $\begingroup$ @kglr, is there any way to put linebreak inside WriteString long expression. WriteString by default writes expression(string) as a single line. $\endgroup$
    – BabaYaga
    Jan 13, 2021 at 22:11
  • 1
    $\begingroup$ @kglr, Agree for writing String. But I needed for some different purpose. I am writing a big expression in the form double var = expr for which I find WriteString convenient so far with only problem is that it writes the expression (Text) in a single line. May be I will open a new thread on this. $\endgroup$
    – BabaYaga
    Jan 14, 2021 at 18:00

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.