2
$\begingroup$

I have two lists,

list1 = {1, 2, 3}
list2 = {4, 5, 6}

I want my CSV file to look like this,

1 4
2 5
3 6

Note that the two lists are created at different times and need to be saved in the CSV file at different times. So I cannot use Transpose and then simply export into the CSV file.

There is a good solution given in https://stackoverflow.com/a/7417916. However, mydata1 and mydata2 are in one column and I want the two data sets to be in separate columns.

$\endgroup$
1
  • 3
    $\begingroup$ Import the existing data from file, add the new column to it in memory, then overwrite the original file with the new data set? $\endgroup$
    – MarcoB
    Sep 16, 2022 at 15:23

1 Answer 1

5
$\begingroup$

As MarcoB suggested,

$Version

(* "13.1.0 for Mac OS X x86 (64-bit) (June 16, 2022)" *)

Clear["Global`*"]

list1 = {1, 2, 3};

Save list1 in CSV file

Export["datafile.csv", list1];

When list2 becomes available

list2 = {4, 5, 6};

Add list2 to data file

Export["datafile.csv",
  Transpose[{
    Import["datafile.csv"] // Flatten,
    list2}]];

Looking at saved data

Import["datafile.csv"]

(* {{1, 4}, {2, 5}, {3, 6}} *)
$\endgroup$
1
  • $\begingroup$ Yeah, this is the solution I was also thinking of. If one wants to add another list to the file, then have to use Export["datafile.csv", MapThread[Append,{Import["datafile.csv"], list3}]] $\endgroup$
    – sslucifer
    Sep 16, 2022 at 16:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.