# LF line break instead of CR+LF when exporting text files on Windows

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?

-

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

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


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

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

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 *** *)

I get {97, 98, 99, 13, 10, 97, 98, 99} from v7 under Windows. –  Mr.Wizard Jan 24 at 16:22
I get {97, 98, 99, 10, 97, 98, 99} from v9, so I guess they fixed something. –  librik Jan 24 at 20:43
I get {97, 98, 99, 13, 10, 97, 98, 99} from v8 under Windows XP. –  Nick Stranniy Jan 24 at 21:57