I'm new here, so please apologize any formal errors.

I stumbled upon a somewhat simple problem. I want to import plain numbers or protected signs like Pi, Cos, Sin from .txt files. Somehow Mathematica does not understand that the read-in Pi is the protected Pi (= 3.14...). Even more simple examples seem not to work, e.g. reading in the number 5 from a .txt-file does not allow for using that 5 for further calculations.

My approach was:

  1. Saving the sign/number in a txt file. E.g. Pi.txt contains just "Pi" (without quotation marks).
  2. My Mathematica code is
x := Import["Pi.txt"]
f[t_] = Sin[t];

Thank you for your help.

  • 2
    $\begingroup$ Try ToExpression[Import["Pi.txt"]] $\endgroup$ Jul 14, 2012 at 18:48
  • 2
    $\begingroup$ The problem is that by default, the contents of a .txt file are read in as a string. Unfortunately, strings and symbols look the same in output form. To check whether your imported expression is a string or a symbol you could do something like x // InputForm. $\endgroup$
    – Heike
    Jul 14, 2012 at 19:10
  • $\begingroup$ Thank you so much. It works just fine. You saved my day. $\endgroup$
    – Joezens
    Jul 14, 2012 at 19:39
  • $\begingroup$ Welcome to Mathematica.SE Joezens! Please consider registering your accounts, so that the upvotes you get on any future questions and answers add to the ones you received here. $\endgroup$
    – Verbeia
    Jul 14, 2012 at 23:09

1 Answer 1


The problem description sounds as if you're in fact trying to import something into Mathematica that is more appropriately classified as a .m format, i.e., a "Package". Let's say your text file contains the single entry


and its name is Pi.txt - then you could simply import it as follows:

variable = Import["Pi.txt", "Package"];

Now variable contains the value Pi. Moreover, your text file can be an entire Mathematica program such as

var1 = Sin[3];
var2 = 4;
var1 + var2

and its file name could be prog.txt - then in Mathematica you could do this:

Import["prog.txt", "Package"]

(* ==> 4 + Sin[3] *)


(* ==> Sin[3] *)

The "Package" format is just a text file containing valid Mathematica expressions.

Things can be made even simpler if you adopt the standard extension for such Mathematica packages by calling the program file prog.m instead of prog.txt. Then the Import statement will be


and you're done.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.