4
$\begingroup$

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.

$\endgroup$

4 Answers 4

5
$\begingroup$
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

?x 

to check that.

Edit

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

x=list[[All, 2]]; 
$\endgroup$
4
  • $\begingroup$ Ahhh, this is better. I don't have to convert from string to expression. $\endgroup$ Commented 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$ Commented Mar 29, 2022 at 19:32
  • $\begingroup$ Transpose[list] should also work, right? $\endgroup$ Commented Mar 29, 2022 at 19:37
  • $\begingroup$ @sslucifer yes, it should also do the trick. you're right :-) $\endgroup$ Commented Mar 29, 2022 at 19:38
5
$\begingroup$
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}}

$\endgroup$
4
$\begingroup$

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.

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

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

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.