0

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?

Wisdom
  • 1,258
  • 7
  • 13

1 Answers1

2

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.

Joshua Schrier
  • 3,356
  • 8
  • 19
  • Thanks a lot. ToExpression what a useful command. why it may be dangerous? – Wisdom May 07 '21 at 12:55
  • 2
    Consider what happens if you evaluated ToExpression on a string that read "DeleteFile[\"*\"]" .... don't try this at home kids.... – Joshua Schrier May 07 '21 at 12:57
  • 2
    @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. – Rohit Namjoshi May 07 '21 at 17:42
  • Ok. many Thanks – Wisdom May 07 '21 at 17:54