2

I need to write into multiple files in a Do loop. Hence, I tried to open multiple streams:

Do[  Symbol[StringJoin["S", ToString[i]] ] = 
  OpenAppend[StringJoin["sf", ToString[i]], 
   FormatType -> OutputForm       ], {i, 1, 10}]

But this gives errors like:

Set::write: Tag Symbol in Symbol[S1] is Protected.
Set::write: Tag Symbol in Symbol[S2] is Protected.

What is the correct way to name the indexed output streams in a Do loop ?

rhermans
  • 36,518
  • 4
  • 57
  • 149

2 Answers2

0

Using SetAttributes firstly I defined func:

SetAttributes[func, HoldFirst]
func[s_, i_] := ( 
  s = OpenAppend[StringJoin["data", ToString[i], ".dat"], 
    FormatType -> OutputForm]  )

Then finally data can be written into files data1.dat and data2.dat as:

Do[Write[func[s, i], i, "\t", i + 10], {i, 1, 2}]
  • Why do you want to do s = OpenAppend[... ? – rhermans Jun 21 '18 at 16:38
  • @rhermans : since I am using s in Write command within Do loop ... Will be good to see alternative ; but this works fine for this toy example .... – Karamveer Kaur Jun 21 '18 at 17:25
  • I don't think it makes sense, you are assigning the output of OpenAppend to the variable s, and then overwriting that value at each iteration. – rhermans Jun 21 '18 at 17:27
0
Array[
  (filehandle[#] = OpenAppend[StringTemplate["File``.txt"][#]]) &
  , 10];

?filehandle

Mathematica graphics

Close /@ Array[filehandle, 10]
rhermans
  • 36,518
  • 4
  • 57
  • 149