0
$\begingroup$

I have a long txt file (which attached here). I want to import this file and then use a special line (in this case line 112) to plot a graph. I tried this

file = Import["data.txt", "Data"];
den = file[[112]];
den // Dimensions
(*
{303}
*)

As you can see it gives me dimensions {303} while the real dimensions of den must be {303,2} I don't know why Mathematica adds an addiional {} to den. Also when I try "Lines" in Import command it returns all of line 112 as a string. What is the best way to import line 112 as a real table as what I really need to plot?

$\endgroup$
2
$\begingroup$

This appears to be an unusual file format which mixes different types of output. Import is attempting to read it as a CSV file, which is causing your problem.

Manual inspection suggests that line 112 is a string representation of a Mathematica List, which suggests that the following should work (using the link you provided). The basic idea is to import the file as a list of strings (one string for each line), and then to interpret the desired line as needed:

file = Import[
   "http://www.deeplook.ir/wp-content/uploads/2021/05/data-1.txt", 
   "List"];
den = ToExpression[ file[[112]] ];
Dimensions[den]  (* {201,2} *)

Warning: It's generally considered dangerous to ToExpression random things on the internet. I looked at line 112 first to see that it was an innocuous List.

$\endgroup$
4
  • $\begingroup$ Thanks a lot. ToExpression what a useful command. why it may be dangerous? $\endgroup$
    – Wisdom
    May 7 '21 at 12:55
  • 2
    $\begingroup$ Consider what happens if you evaluated ToExpression on a string that read "DeleteFile[\"*\"]" .... don't try this at home kids.... $\endgroup$ May 7 '21 at 12:57
  • 2
    $\begingroup$ @Wisdom As I mentioned in my comments here, using Print to save several WL expressions to a file and then trying to reconstruct them by reading the file as a string is clunky and brittle. Much better to use Put, or PutAppend, and Get. $\endgroup$ May 7 '21 at 17:42
  • $\begingroup$ Ok. many Thanks $\endgroup$
    – Wisdom
    May 7 '21 at 17:54

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.