6

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?

wdg
  • 1,189
  • 9
  • 18

3 Answers3

8

You could use ReadList:

ReadList["test.dat", String]
(* {"01011", "00101", "01011"}  *)
Simon Woods
  • 84,945
  • 8
  • 175
  • 324
6

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"}} *)
Ajasja
  • 13,634
  • 2
  • 46
  • 104
  • 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? – wdg Jan 23 '14 at 17:11
  • 4
    @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. – Ajasja Jan 23 '14 at 17:15
  • 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 (http://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:) – Ajasja Jan 23 '14 at 21:00
  • @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. – wxffles Jan 23 '14 at 23:38
4
str = "01011\n00101\n01011";
ImportString[str, "Lines"] 

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

Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323