View Single Post
Bill Simpson
#6
Apr18-11, 02:54 PM
P: 1,037
This may be somewhat Mathematica-version dependent, but let's see what we can do for you.

I created a tiny text file containing 3 characters
1\n2
where \n represents tapping the Enter key.

To simplify this whole directory business I put that in my C:\Program Files\Wolfram Research\Mathematica\x.y directory, where x.y is my current version number. You can test using that method or if you have your directory handling figured out you can ignore this.

I then hopped into Mathematica and did this (literally copying and pasting exactly my notebook cell contents). Note: My textual description not preceded by In[] or Out[] was not part of my notebook contents, it is just to explain what is going on.

In[1]:= Import["numbers.txt"]
Out[1]=
1
2

But Mathematica will often "lie to you", presenting things that look like one thing but are another. FullForm will more often show you what something really is.

In[2]:= FullForm[%]
Out[2]//FullForm= "1\n2"

So that read the file as a single string and that isn't convenient.

So then I did exactly this

In[3]:= Import["numbers.txt","Lines"]
Out[3]= {1,2}

That looks exactly like what I think you want, but I bet it isn't.

In[4]:= FullForm[%]
Out[4]//FullForm= List["1","2"]

That is a list of strings and you almost certainly want a list of numbers. So ToExpression will help you.

In[5]:= ToExpression[%]
Out[5]= {1,2}

In[6]:= FullForm[%]
Out[6]//FullForm= List[1,2]

You can then bundle this up and also verify the format using this.

In[7]:= mynumbers=ToExpression[Import["numbers.txt","Lines"]]
Out[7]= {1,2}

In[8]:= FullForm[mynumbers]
Out[8]//FullForm= List[1,2]

As a general rule, I think making a copy of your notebook, editing the copy, and any needed data files, down to the point where it contains everything needed and nothing more for someone else who knows nothing about what is already in your head to be able to demonstrate exactly what the problem or the solution is, restarting Mathematica, or killing the kernel, evaluating all the cells in the notebook in order and then carefully copy-and-pasting all the notebook into a posting is the most likely way to get a good solution on the first try.

Are there at least a dozen different ways of accomplishing almost anything in Mathematica, including at least three that are completely incomprehensible? Yes.