Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
Try ToExpression[Import["Pi.txt"]] – b.gatessucks Jul 14 '12 at 18:48
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. – Heike Jul 14 '12 at 19:10
Thank you so much. It works just fine. You saved my day. – Joezens Jul 14 '12 at 19:39
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. – Verbeia Jul 14 '12 at 23:09

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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