How to write a string verbatim

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.


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

Tags:

Output