I have a set of text files named in indexed way d1, d2, d3, d4, d5, d6, d7, d8, d9.

I want to read them by Mathematica and export them back with other index names N(s1f1+s1f1), N(s1f1+s2f2), N(s1f1+s3f3),N(s2f2+s1f1), N(s2f2+s2f2), N(s2f2+s3f3),N(s3f3+s1f1), N(s3f3+s2f2), N(s3f3+s3f3)

I did a for loop as follows

 For[i = 1, i <= 3, i++, 
  For[j = 1, j <= 3, j++, 
   For[k = 1, k <= 3, k++, 
    Export[StringJoin["N", "(", "s", TextString[i], "f", 
      TextString[i], "+", "s", TextString[j], "f", TextString[j], ")",
       ".txt"], Import[StringJoin["d", TextString[k], ".txt"]]]]]];

But the problem is the resulting files contain data from d9 only

  1. You don't need to import and export files just to rename them. You can just use RenameFile to carry out the renaming for you.
  2. For loops, and procedural loops in general, are not recommended in Mathematica; see Alternatives to procedural loops and iterating over lists in Mathematica and Why should I avoid the For loop in Mathematica?.

Here is an alternative to explicit procedural looping that uses Tableand MapThread to feed the names to RenameFile:

  RenameFile[Echo@#1, Echo@#2] &,
    Table[StringJoin["d", k, ".txt"], {k, CharacterRange["1", "9"]}],
      StringJoin["N", "(s", i, "f", i, "+s", j, "f", j, ").txt"],
      {i, CharacterRange["1", "3"]}, {j, CharacterRange["1", "3"]}

I also avoid the conversions of the numbers to strings (which, by the way, would be more conveniently carreid out by ToString rather than TextString) by providing the string numerals instead of the numbers as values of the iterators in the Tables.

  • $\begingroup$ Thank you very much. It works well now $\endgroup$ – Amr Saleh Apr 1 at 18:35
  • $\begingroup$ @AmrSaleh You are very welcome. If you think that my answer solves your problem, you can also upvote it / accept it by ticking the gray checkmark close to it. $\endgroup$ – MarcoB Apr 1 at 19:00

You can generate the filenames you need using Table:

filenames = Flatten[Table[{StringJoin @ MapThread[Riffle, 
     {{{"N(s", "f", "+"}, {"s", "f", ").txt"}}, ToString /@ {i, j}}],
    StringJoin["d", TextString[j + 3 (i - 1)], ".txt"]},
  {i, 3}, {j, 3}], 1]
{{"N(s1f1+s1f1).txt", "d1.txt"}, 
 {"N(s1f1+s2f2).txt", "d2.txt"},
 {"N(s1f1+s3f3).txt", "d3.txt"}, 
 {"N(s2f2+s1f1).txt", "d4.txt"},
 {"N(s2f2+s2f2).txt", "d5.txt"},
 {"N(s2f2+s3f3).txt", "d6.txt"},
 {"N(s3f3+s1f1).txt", "d7.txt"},
 {"N(s3f3+s2f2).txt", "d8.txt"}, 
 {"N(s3f3+s3f3).txt", "d9.txt"}}

Then use

Export[#, Import@#2] & @@@ filenames
  • $\begingroup$ Thank you for help $\endgroup$ – Amr Saleh Apr 1 at 18:37
  • $\begingroup$ @AmrSaleh, you are most welcome. $\endgroup$ – kglr Apr 1 at 18:40

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.