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 am working my way through Programming Paradigms via Mathematica (A First Course) and have answered the following question in lesson 25:

Write a function of one argument "s", a String, which writes the string "s" to some file and then reads the string that file back in as a list of single characters. This operation thus mimics Characters[]. Pay attention to the methods Mathematica has for reading in data from a file.

In   Characters["the cow jumped over the moon"]

 Out   {t, h, e,  , c, o, w,  , j, u, m, p, e, d,  , o, v, e, r,  , t, h, e,  , m, o, o, n}

My function is as follows:

myCharacters[s_String] :=
   myStream = OpenWrite["file2"];
   Write[myStream, s];
   ReadList["file2", Character]
myCharacters["the cow jumped over the moon"]

which produces an output that includes the leading and trailing quotation marks:

{",t, h, e,  , c, o, w,  , j, u, m, p, e, d,  , o, v, e, r,  , t, h, e,  , m, o, o, n,"}

So thinking back to my previous question, where I had a couple of significant mistakes, I am wondering if there is something that I am missing or is my answer basically correct? Also I would appreciate being shown how I could improve my function even if it does give correct output.

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

The one-line fix is to use WriteString in place of Write. This writes the literal string rather than the corresponding Mathematica expression, which is delimited by quotation marks.

The same thing could be accomplished by using BinaryWrite because as the documentation states:

BinaryWrite[channel,"string"] writes the raw sequence of characters in a string.

To use it however you must open your stream appropriately:

OpenWrite["file2", BinaryFormat -> True]

If you are not set on using streams this can be done more simply with Export as unlike Write or Put this function can conveniently write raw strings (again, rather than Mathematica String expression syntax).

myCharacters[s_String] := ReadList[Export["$file", s, "String"], Character]

Note that since Export returns the name of the file I used it inside ReadList directly.

share|improve this answer
Mr. Wizard, thank you for your help. –  Clif Aug 16 '13 at 1:15
add comment

Your Answer


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.