1
$\begingroup$

So I have a textfile looking like this:

0.15 0.2 10 0 0 0 0.2 0.5 0.1 0.01 100000 1000000 100000

Now I want to Import the third entry of the line.
I have tried it like this:

Import[".../Desktop/data.txt", {"Data", {3}}]

But I got this error `"The Import element "3" is not present when importing as Text.

$\endgroup$
1
  • $\begingroup$ You can also just do Import[file, "Table"][[1, 3]] (or some minor variant on that) $\endgroup$
    – b3m2a1
    Jan 7, 2018 at 19:18

2 Answers 2

2
$\begingroup$

Assuming that you have only reals numbers separated by spaces:

ToExpression@TextWords[Import["input.txt"]][[3]]

(* 10 *)

does the job.

$\endgroup$
4
  • $\begingroup$ More efficient would just be a StringSplit[line, " ", 4][[3]] $\endgroup$
    – b3m2a1
    Jan 7, 2018 at 19:10
  • $\begingroup$ Why "more efficient"? and, the OP maybe needs the number and not the string... $\endgroup$ Jan 7, 2018 at 19:14
  • 1
    $\begingroup$ I was assuming you'd just use the ToExpression again. Performance wise comparing ToExpression@TextWords[line][[3]] // RepeatedTiming // First and ToExpression@StringSplit[line, " ", 4][[3]] // RepeatedTiming // First there's over an order of magnitude gain. $\endgroup$
    – b3m2a1
    Jan 7, 2018 at 19:15
  • $\begingroup$ Even more efficient ToExpression@StringSplit[Import["input.txt"]][[3]] ... ;)) $\endgroup$ Jan 7, 2018 at 19:19
2
$\begingroup$

You can use streams:

stream = OpenRead["text.txt"];
Skip[stream, Number, 2];
Read[stream, Number]
Close[stream];

10

I'm not sure how fast it is, I have only used it for binary files where instead of Skip one can use SetStreamPosition which is very fast.

$\endgroup$
3
  • 1
    $\begingroup$ You can do this with a single ReadList, too. i.e. ReadList[file, Number, 3][[3]]. And ReadList will auto-open and auto-close, cutting out that part of the code. $\endgroup$
    – b3m2a1
    Jan 7, 2018 at 19:17
  • $\begingroup$ @b3m2a1 Yes but then mathematica won't understand that the first n-1 entries should be discarded immidiately. A list will be constructed just to take a single element $\endgroup$
    – Coolwater
    Jan 7, 2018 at 19:19
  • $\begingroup$ True, but that will only really matter at very, very large values of n. $\endgroup$
    – b3m2a1
    Jan 7, 2018 at 19:19

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.