1
$\begingroup$

Consider generated numerical data with added symbolical row:

data = RandomReal[1, {10, 5}]
data2 = Join[{{"Value 1", "Value 2", "Value 3", "Value 4", 
    "Value 5"}}, data]

Now, consider we made export and then want to import the data:

SetDirectory[NotebookDirectory[]];
    Export["data2.dat", data2]
  data3 = Import["data2.dat"]

The text column which is displayed correctly in initial data2 in data3 is displayed incorrectly. Namely, the spaces are replaced by commas, which results in different length of row with symbols and row with numbers.

How to force Mathematica to import the file correctly? I thought that "" would help, but they didn't...

$\endgroup$

3 Answers 3

2
$\begingroup$

Probably it's best to explicitly name the format, in this case "TSV". as the separation between fields are tabular characters (ToCharacterCode["\t"] -> 9).

InputForm@Import["data2.dat", "TSV"]

Mathematica graphics

The data as saved in the file "data2.dat" is "TSV" and not "CSV"

Mathematica graphics

$\endgroup$
1
$\begingroup$

You could compress the sublist with strings:

Export["data2.dat", MapAt[Compress, data2, 1]]
data3 = MapAt[Uncompress@*First, Import["data2.dat"], 1]
data3 === data2

True

$\endgroup$
1
$\begingroup$
Export["d:\\2018\\data2.dat", data2 ]
data3 = Import["d:\\2018\\data2.dat", "TSV"]
Simplify[data2==data3]
(*True*)

works fine!

$\endgroup$
6
  • $\begingroup$ But the data, as saved, is "TSV" and not "CSV". $\endgroup$
    – rhermans
    Jul 27, 2018 at 14:42
  • $\begingroup$ Where "TSV" appears? data and data2 are comma separated lists, so I export/import as "CSV"! $\endgroup$ Jul 27, 2018 at 14:50
  • $\begingroup$ The data in the OP is "TSV". $\endgroup$
    – rhermans
    Jul 27, 2018 at 14:50
  • $\begingroup$ data2 =={{"Value 1", "Value 2", "Value 3", "Value 4", "Value 5"}, {0.0348347, 0.0162931, 0.26708, 0.4453, 0.910656},...} $\endgroup$ Jul 27, 2018 at 14:53
  • 1
    $\begingroup$ Now I got it!!! My answer is edited. $\endgroup$ Jul 27, 2018 at 14:56

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.