12

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?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Nick Stranniy
  • 1,233
  • 9
  • 15

2 Answers2

10

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]
librik
  • 1,526
  • 9
  • 12
4

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.

Nick Stranniy
  • 1,233
  • 9
  • 15