# How to write a UTF-8 file?

s = OpenWrite[ofile, CharacterEncoding -> "UTF8"]
Export[s, "∂f/∂t"]
Close[s]


did not successfully write ∂ into the file. Instead, it writes the InputForm. How to let it write ∂?

-
AFAIK Export and OpenWrite have no relationship whatsoever. I find it a small wonder that you can even use a file handle in Export. –  Sjoerd C. de Vries Sep 9 '12 at 22:40
Really? No wonder. My guess is Export[file, ...] internally will create file handle any way and using file handle directly probably just mean a replacement didn't occur. It might be an accident due to implementation details. –  Problemania Sep 9 '12 at 23:03

F'x is correct. Using WriteString is the method to use. If you want to write a "big expression", try the following.

Let's assume a large matrix with dimensions of 100 by 5;

a = RandomReal[{1,10},{100,5}]


We can easily write this using the WriteString method.

s = OpenWrite["~/Desktop/toto.txt", CharacterEncoding -> "UTF8"]
WriteString[s, a]
Close[s]


This will write to the text file exactly as you see it printed in the notebook interface.

You can also print in Grid or TableForm

a = RandomReal[{1,10},{100,5}]//TableForm


You can also get a little crazy and riffle in delimiters...

a = "a =   "<> StringJoin[Riffle[ToString[#^2] & /@ Range[10], "\t"]]


Also, don't forget the OpenAppend function to write data at the end of a file without overwriting existing info.

b = "b =   " <> StringJoin[Riffle[ToString[#^3] & /@ Range[10], "\t"]]
s = OpenAppend["~/Desktop/toto.txt", CharacterEncoding -> "UTF8"]
WriteString[s, "\n"]
WriteString[s, b]
Close[s]

-
WriteString:
s = OpenWrite["~/Desktop/toto.txt", CharacterEncoding -> "UTF8"]