12
$\begingroup$

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"];
BinaryReadList[testFile]

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?

$\endgroup$

2 Answers 2

10
$\begingroup$

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 *** *)
BinaryReadList[testFile]
$\endgroup$
3
  • $\begingroup$ I get {97, 98, 99, 13, 10, 97, 98, 99} from v7 under Windows. $\endgroup$
    – Mr.Wizard
    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
    Jan 24, 2013 at 20:43
  • $\begingroup$ I get {97, 98, 99, 13, 10, 97, 98, 99} from v8 under Windows XP. $\endgroup$ Jan 24, 2013 at 21:57
4
$\begingroup$

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.

$\endgroup$
2
  • 1
    $\begingroup$ (+1) perhaps you can turn your code into a custom ExportConverter ? $\endgroup$
    – kglr
    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
    Jan 25, 2013 at 2:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.