# Write macro to file at runtime and \input the content

Let me give it as an example:

I want to write some commands to a file

\newwrite\tempfile
\immediate\openout\tempfile=mycommands
\immediate\write\tempfile{"\toprule"}%Yes it don't work like this!
\immediate\closeout\tempfile


Then somewhere after:

\begin{tabular}{r l l l l l l l}

• Why do you want to write this to a file? If it's just contents you need to create during runtime you could as well define a global macro that stores the contents. – Skillmon likes topanswers.xyz Oct 22 '19 at 12:07
• My problem is different, the above case is just an example. – Reza Afzalan Oct 22 '19 at 12:16
• In that case it might be a good idea to explain your use case. – Skillmon likes topanswers.xyz Oct 22 '19 at 12:21

You must prevent expansion when writing to the file. And you can't use \input to load the file if it starts e.g. with a \toprule: \input is not expandable and so not allowed in this place. The primitive input command will work.

\documentclass{article}
\usepackage{booktabs}
\begin{document}
\newwrite\tempfile
\immediate\openout\tempfile=mycommands.txt
\immediate\write\tempfile{\unexpanded{\toprule}}%
\immediate\closeout\tempfile

\begin{tabular}{r l l l l l l l}
\csname @@input\endcsname mycommands.txt
abc\\
\end{tabular}
\end{document}