# How to write a string verbatim

I'm trying to write a function which takes some strings, manipulates them, and writes the result to a file.

Here's a small example which recreates the behavior I'm seeing:

writefile[instr1_, instr2_, filename_] :=
Module[{str1, outstr, stream},
str1 = "abc \n  \n def \n ";
outstr = OutputForm[StringForm[str1, instr1, instr2]];
Export[filename, outstr];
]


When I call writefile["xyz", "pqr", "test.txt"], I would expect test.txt to have the output:

abc
xyz
def
pqr


However, it instead looks like this:

abc xyz     pqr
def


What's going on? I've tried the suggestions at this SE, but they all give the same result.

When I remove the OutputForm call and simply return outstr in the function above, it prints to the screen just fine, but writing this to file means that the output file reads literally StringForm["abc \n  \n def \n ", "xyz", "pqr"].

Do not use OutputForm. Use StringTemplate. This is sufficient to generate your string:

In[191]:= templ = StringTemplate["abc \n  \n def \n "];

In[192]:= templ["xyz", "pqr"]
Out[192]= "abc
xyz
def
pqr"


Those extra spaces at the beginning of each line are there because you added them to the template, after each \n. Remove them if you don't want them.

You can now Export this string. It is a good idea to always specify the export format explicitly. Do not do Export[filename, str] because the export format will be inferred from the file name. Use Export[filename, str, "String"] for raw strings or Export[filename, str, "Text"] if you want to specify things like character encodings and line endings.

• Thanks! this did it Mar 12, 2020 at 15:16

I think this would do what you want:

writefile[instr1_, instr2_, filename_] :=
Module[{str1, outstr, stream},
str1 = "abc\n" <> instr1 <> "\n" <> "def\n" <> instr2 <> "\n";
outstr = OutputForm[StringForm[str1]];
Export[filename, outstr];]


Calling this with

writefile["xyz", "pqr", "test.txt"]


Gives the following file contents (each is on a separate line): abc xyz def pqr