I want my program to always save a text file with unix-style LF line breaks (even when Mathematica runs on Windows). But the way the built-in Export command works depends on the operating system.

For example the following code:

testFile = "newlinetest.txt";
testStringList = {"abc", "abc"};
Export[testFile, testStringList, "List"];

Linux or Mac OS gives exactly what I want:

{97, 98, 99, 10, 97, 98, 99}

Windows adds an extra CR symbol:

{97, 98, 99, 13, 10, 97, 98, 99}

Is there a normal way to save text files with unix-style newline on Windows?


2 Answers 2


The default when a file stream is opened on Windows is to open it as a Windows text file, which uses CR/LF line terminators. To open a stream with no Windows text file translations, use OpenWrite with the BinaryFormat->True option.

You can pass a stream that you opened with OpenWrite to Export in place of a file name. Remember to Close the stream when you are done writing to it!

(When you pass a file name rather than a stream, Mathematica's I/O functions (like Export) will take care of opening and closing the file for you, but you'll have no control over how it's opened. Since you want control, don't pass a file name.)

testFile = "newlinetest.txt";
testStringList = {"abc", "abc"};
testStream = OpenWrite[testFile, BinaryFormat->True];  (* *** open it yourself *** *)
Export[  testStream  , testStringList, "List"];        (* *** pass the stream *** *)
Close[testStream];                                     (* *** close it yourself *** *)
  • $\begingroup$ I get {97, 98, 99, 13, 10, 97, 98, 99} from v7 under Windows. $\endgroup$
    – Mr.Wizard
    Commented Jan 24, 2013 at 16:22
  • $\begingroup$ I get {97, 98, 99, 10, 97, 98, 99} from v9, so I guess they fixed something. $\endgroup$
    – librik
    Commented Jan 24, 2013 at 20:43
  • $\begingroup$ I get {97, 98, 99, 13, 10, 97, 98, 99} from v8 under Windows XP. $\endgroup$ Commented Jan 24, 2013 at 21:57

I ended up with using BinaryWrite function. It's kind of messy but works.

BinaryWrite[testFile, Flatten[Riffle[ToCharacterCode[testStringList], {10}]]];

In principle there should be some kind of LineSeparator option for Export but i couldn't find it.

  • 1
    $\begingroup$ (+1) perhaps you can turn your code into a custom ExportConverter ? $\endgroup$
    – kglr
    Commented Jan 23, 2013 at 23:51
  • $\begingroup$ +1 As John Fultz commented under my (deleted) answer, now I think binary I/O might be the best choice. $\endgroup$
    – Silvia
    Commented Jan 25, 2013 at 2:58

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.