8
$\begingroup$

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 ?

$\endgroup$

1 Answer 1

9
$\begingroup$
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

$\endgroup$
6
  • 1
    $\begingroup$ Consider also mentioning WriteString +1 $\endgroup$ Commented Apr 23, 2015 at 23:31
  • $\begingroup$ Thanks @Mr.W, added WriteStream. $\endgroup$ Commented Apr 23, 2015 at 23:46
  • $\begingroup$ Great ! Thank you $\endgroup$ Commented 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$ Commented 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$ Commented Jan 14, 2021 at 18:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.