Message Boards Message Boards


Export all variables of a notebook in a text file?

Posted 4 months ago
2 Replies
1 Total Likes

Hi, I would like to export all variables of a notebook in a text file, in two columns: name of variables and variable value. For instance,let's consider the notebook:

In[1]:= a = 20

b = 3

c = 10

Out[1]= 20

Out[2]= 3

Out[3]= 10

The file, let's name it "output.txt" should be as follows:

a = 20

b = 3

c = 10

Thank you in advance.

2 Replies
Posted 4 months ago


It really depends on exactly what you mean by "variable". Is a function definition a "variable"? Is a symbol with a Head of List a "variable"? For the simple case in your question the following will work. For more complex cases you will have to filter the list of symbols to exclude symbols that you do not consider to be "variables".

a = 20; b = 3; c = 10;

Names["Global`*"] // 
     Map[{# <> " = " <> ToString[Evaluate[ToExpression[#]]]} &] //
     Flatten //
     StringRiffle[#, "\n"] & //
     Export["output.txt", #] &;

Thank you very much, Rohit. I tried it and works well. I need that for a work colleague: he is blind and manages simple notebooks for his evaluations. A text output is safe since he can read and edit it (cutting away unnecessary variables) with spelling software, so he can use it for further work on it.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract