# Writing math in an auxiliary file : what happens to underscore?

Using newfile extension, I am writing content to an external file.

However, when this content contains underscore in math formula, it is written in the external file with a space before the underscore symbol. For example :

\documentclass{article}

\usepackage{newfile}

\newoutputstream{testout}
\openoutputfile{testout.out}{testout}

\begin{document}
\begin{writeverbatim}{testout}
First test $\sum_{i=1}^n x_i$
\end{writeverbatim}

\addtostream{testout}{Second test, and underscore_test $\sum_{i=1}^n x_i$}

\closeoutputstream{testout}
\end{document}


produces the following testout.out :

First test $\sum_{i=1}^n x_i$
Second test, and underscore_test $\sum _{i=1}^n x_i$


where you can notice the space before the underscore in the second formula, while it is not the case in the first formula.

It is not really a big problem for what I want to do, but if someone knows how to get rid of these spaces, it would be great.

However, my question is mainly why does this happen ?

It is not that a space is written before the_ it is a space written after \sum. This is a primitive behaviour of TeX when writing command names so that \sum x does not get written as \sumx.
If you make \sum not be a token but rather a sequence of four characters then this space will not be added, so changing the catcode of \ or using \string\sum before writing the characters would stop the space being added.