5
$\begingroup$

I have a file that contains binary strings like

01011
00101
01011

I want to import the file to Mathematica as a list of strings, but

Import["test.dat", "Table"]

gave me

{{1011}, {101}, {1011}},

which is a list of numbers rather than strings.

What should I do to make sure that the binary strings are read as strings rather than numbers?

$\endgroup$
8
$\begingroup$

You could use ReadList:

ReadList["test.dat", String]
(* {"01011", "00101", "01011"}  *)
$\endgroup$
6
$\begingroup$

You have to learn how to use the help file (Do press F1 as often as possible, although to be fair the option is a bit hidden). You are looking for "Numeric"->False option. It can be found by pressing F1 when the text cursor is over Import, click listing of formats, click Table and then option:

str = "01011\n00101\n01011"
ImportString[str, "Table"]
ImportString[str, "Table", "Numeric" -> False]

(*=> {{1011}, {101}, {1011}} *)    
(*=> {{"01011"}, {"00101"}, {"01011"}} *)
$\endgroup$
  • $\begingroup$ I did notice ImportString while I was searching the help files. However, ImportString reads from a string. Did you suggest that I have to copy and paste the file contents rather than reading from a file by giving the filename? $\endgroup$ – wdg Jan 23 '14 at 17:11
  • 4
    $\begingroup$ @wdg No, not at all. Import and ImportString take the same options. I used ImportString because it's easier to create a self contained example. $\endgroup$ – Ajasja Jan 23 '14 at 17:15
  • $\begingroup$ 5 upvotes for this simple answer, that took me las than 5 min to write as a break? Well thank you. But on this answer (mathematica.stackexchange.com/a/40687/745) I spent more than 3 hours and it only got 2 upvotes. Hmm, I still don't fully understand how mma.se works:) $\endgroup$ – Ajasja Jan 23 '14 at 21:00
  • $\begingroup$ @Ajasja It's because it's simple. Easy to understand the problem and easy to understand the answer. The other question/answer is big and intimidating. $\endgroup$ – wxffles Jan 23 '14 at 23:38
4
$\begingroup$
str = "01011\n00101\n01011";
ImportString[str, "Lines"] 

{"01011", "00101", "01011"}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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