Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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
SetDirectory["C:\\Code"];
x := Import["Pi.txt"]
f[t_] = Sin[t];
Evaluate[f[x]]

Thank you for your help.

share|improve this question
2  
Try ToExpression[Import["Pi.txt"]] –  b.gatessucks Jul 14 '12 at 18:48
2  
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
add comment

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

Pi

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] *)

var1

(* ==> 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

Import["prog.m"]

and you're done.

share|improve this answer
add comment

Your Answer

 
discard

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.