8

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 ?

Aug
  • 385
  • 4
  • 10

1 Answers1

9
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]
Close[strm]

to get the same result:

enter image description here

Nitin
  • 431
  • 2
  • 8
kglr
  • 394,356
  • 18
  • 477
  • 896
  • 1
    Consider also mentioning WriteString +1 – Mr.Wizard Apr 23 '15 at 23:31
  • Thanks @Mr.W, added WriteStream. – kglr Apr 23 '15 at 23:46
  • Great ! Thank you – Aug Apr 23 '15 at 23:59
  • @kglr, is there any way to put linebreak inside WriteString long expression. WriteString by default writes expression(string) as a single line. – BabaYaga Jan 13 '21 at 22:11
  • @Boogeyman, afaik we can't do it directly with WriteString. You can use WriteLine instead. – kglr Jan 14 '21 at 17:48
  • 1
    @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. – BabaYaga Jan 14 '21 at 18:00