0
$\begingroup$

I have 2370 table which I need to export in cvs format with different name and I don't want to do it manually. Let say I have this 3 tables:

table1=Table[{i,i+1},{i,1,8}]
table2=Table[{j,2*j},{j,1,12}]
table3=Table[{k,5+k},{k,1,4}]

I tried to export them by For loop (which did not work) by below code.

For[i=1,i<=3,i++,Export["tablei.cvs",tablei,"Table"]]

What is the right way to do it? Thank you for your help.

$\endgroup$
0

2 Answers 2

2
$\begingroup$

It's better to use this. But if you use tableXXXX, use the method in the comment.

table[1]=Table[{i,i+1},{i,1,8}]
table[2]=Table[{j,2*j},{j,1,12}]
table[3]=Table[{k,5+k},{k,1,4}]
Export["table"<> ToString[#] <>".cvs",table[#],"Table"]] &/@ Range[1,3]
$\endgroup$
2
  • $\begingroup$ All of my table are inside another table so I can access to them just by tableformt[[i]] (tableformat is the name of the table of the table that I have), above solution works but problem is that it create list not table in cvs format. $\endgroup$
    – Parviz
    Feb 11, 2022 at 20:00
  • $\begingroup$ I can export them one by one by this command (Export["1.cvs", tableformat[[1]], "Table"]) then export all of them by For loop or Do or another Table but problem is how to change the name for each table. $\endgroup$
    – Parviz
    Feb 11, 2022 at 20:04
1
$\begingroup$

Here is one approach that may help. Consider the following three functions. The first function, tname, returns a table name as a string. For example, "table0053". The second function, fname returns a file name. For example, "table0053.csv". The third fundtion, vname, returns a variable name. For example, table0053.

ClearAll[tname, fname, vname, "table*"]
tname[n_] := "table" <> StringJoin[ToString /@ IntegerDigits[n, 10, 4]]
fname[n_] := tname[n] <> ".csv"
vname[n_] := ToExpression[tname[n]]

We can use these functions to generate the tables. Importantly, in order to use vname on the left of the = (Set command), we must Clear the variable name and use Evaluate. The following code creates three variables, table0053, table0192 and table2301.

Evaluate[vname[53]] = Table[{i, i + 1}, {i, 1, 8}];
Evaluate[vname[192]] = Table[{j, 2*j}, {j, 1, 12}];
Evaluate[vname[2301]] = Table[{k, 5 + k}, {k, 1, 4}];

table2301

(*  {{1, 6}, {2, 7}, {3, 8}, {4, 9}}  *)

To list the names of all of the table variables, use Names["table*"]. Now we can export a single table like this

Export[fname[2301], vname[2301], "CSV"];
Import[%, "Text"]

(*  "1,6
    2,7
    3,8
    4,9"  *)

A sequence of tables can be exported like this

Do[Export[fname[k], vname[k], "CSV"],
 {k, {53, 192, 2301}}]
$\endgroup$

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.