I have a txt file "data.txt". This contain data like

a   1
b   2
c   3

I want to import this file into two list like $\{a,b,c\}$ and $\{1,2,3\}$.I have tried using SplitBy, but no luck.


4 Answers 4

list=Import["finename.txt", "Table"]

should do the trick. With the following you should be able to assign values, i.e get a list of explicit assigned values

MapIndexed[(x[#2[[1]]] = #1[[2]]) &, list];

You can use


to check that.


If you want an array I think the following should do the trick:

x=list[[All, 2]];
  • $\begingroup$ Ahhh, this is better. I don't have to convert from string to expression. $\endgroup$
    – sslucifer
    Mar 29, 2022 at 19:30
  • 1
    $\begingroup$ @sslucifer glad I was able to help. Maybe you should check the edit in case you want an array. That should also work I think. $\endgroup$
    – bmf
    Mar 29, 2022 at 19:32
  • $\begingroup$ Transpose[list] should also work, right? $\endgroup$
    – sslucifer
    Mar 29, 2022 at 19:37
  • $\begingroup$ @sslucifer yes, it should also do the trick. you're right :-) $\endgroup$
    – bmf
    Mar 29, 2022 at 19:38
d3 = ReadList["C:/data.txt", Record, RecordSeparators -> {"\n"}, 
  WordSeparators -> {"\t", " "}]

{"a 1", "b 2", "c 3"}

Now you can convert this list of strings to expressions and execute Transpose (assuming that's what you want);

Transpose@ToExpression@(StringSplit /@ d3)

{{a, b, c}, {1, 2, 3}}


Not sure what representations you eventually want, but if you import it as a string...

data = Import[pathtofile]

...then you can start with StringSplit...

list = StringSplit[data]

...from there you can partition and reorganize...

Transpose[Partition[list, 2]]

Now, the individual elements are still strings, but I don't know what you want them to be. You may need to apply more transformations or you may want to use import options.

  • $\begingroup$ Thanks, it works. I wanted all the numbers in float, so I used ToExpression to convert all the strings to numbers. $\endgroup$
    – sslucifer
    Mar 29, 2022 at 19:27

One possibility :

data =
  "a 1
b 2
c 3";

file = Export[FileNameJoin[{$TemporaryDirectory, "test.txt"}], data]

ReadList[file, Word, RecordLists -> True]  

{{"a", "1"}, {"b", "2"}, {"c", "3"}}

Then use Transpose


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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