2
$\begingroup$
list= {{}, {200, 200, 200}, {}, {201, 201}};
Export["list.csv", {list}, "csv"]
data = Import["lnumber.csv", "csv"];

The result of this export and import is an extra curly bracket.

 (* data -> {{{}, {200, 200, 200}, {}, {201, 201}}} *)

(Note:without " "in output).

However, I want {200, 200, 200, 201, 201}.

Flatten[data] doesn't give the desired result. One way to overcome the problem is to Flatten[list] before exporting.

But, I want to Flatten[data] to get the desired result.

$\endgroup$
2
$\begingroup$

Your usage of "CSV" export is incorrect: exported list of numbers should be a 2D numerical array, while with {list} you supply a 3D array. With correct "CSV" format you can use advanced Import options:

list = {{}, {200, 200, 200}, {}, {201, 201}};
Export["list.csv", list, "CSV"];
data = Import["list.csv", "Table", "FieldSeparators" -> ","]
{{}, {200, 200, 200}, {}, {201, 201}}
Flatten[%]
{200, 200, 200, 201, 201}

Note that in version 8.0.4 the following does the job even better :

Import["list.csv", "CSV", "IgnoreEmptyLines" -> True]
{{200, 200, 200}, {201, 201}}

For some reason in versions 11.2.0 and 11.3.0 the option "IgnoreEmptyLines" -> True does nothing, what looks like a bug.

$\endgroup$
3
$\begingroup$

However, I want {200, 200, 200, 201, 201}

Try

 data=Import["list.csv","CSV"]
 Flatten@ToExpression[data]

Mathematica graphics

$\endgroup$
  • $\begingroup$ Exactly what I was looking for! $\endgroup$ – Mark Robinson Nov 19 '17 at 8:55
2
$\begingroup$

A few points. First, you are not importing the same file that you're exporting. Is that intentional?

Secondly, the extra bracket is due to the extra bracket in the Export line:

Export["list.csv", {list}, "csv"]

Is not exactly the same as:

Export["list.csv", list, "csv"]

The latter exports list in .csv format, while the former exports a list containing list in .csv format. If you make that change, the extra bracket will disappear.

With that change, it is worth noting that the empty lists are imported as {""} (check FullForm[data] to see for yourself). This will result in spurious empty spaces showing up in Flatten[data]. DeleteCases can be used to clean it up:

DeleteCases[Flatten[data],""]
$\endgroup$
  • $\begingroup$ Sorry for the typo in filename. And thanks for the detailed answer. $\endgroup$ – Mark Robinson Nov 19 '17 at 8:44

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.