Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

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.

share|improve this answer
1  
(+1) perhaps you can turn your code into a custom ExportConverter ? –  kguler Jan 23 '13 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 '13 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 *** *)
BinaryReadList[testFile]
share|improve this answer
    
I get {97, 98, 99, 13, 10, 97, 98, 99} from v7 under Windows. –  Mr.Wizard Jan 24 '13 at 16:22
    
I get {97, 98, 99, 10, 97, 98, 99} from v9, so I guess they fixed something. –  librik Jan 24 '13 at 20:43
    
I get {97, 98, 99, 13, 10, 97, 98, 99} from v8 under Windows XP. –  Nick Stranniy Jan 24 '13 at 21:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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