# Naming indexed output streams

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 ?

• Probably you should read this question:" What are the requirements for a well behaved indexed variable?" – rhermans Jun 21 '18 at 13:37
• Also, check Attributes[Set], it includes HoldFirst, so the left hand side of = (Set) is held. – rhermans Jun 21 '18 at 13:42
• By the way, welcome to Mma.SE! start by taking the tour now. It helps us to help you when you write an excellent question. You can always edit if improvable, to show due diligence, give brief context, include minimal working example of code and data in formatted form. As you receive give back, vote and answer questions, keep the site useful, be kind, correct mistakes and share what you have learned. – rhermans Jun 21 '18 at 13:44
• @rhermans Thanks for your reply ... Instead of joining strings now I am naming the output streams with subscripts -- Subscript[ S , i ] and it's working !! – Karamveer Kaur Jun 21 '18 at 13:54
• You should avoid using Subscript while defining symbols (variables). Subscript[x, 1] is not a symbol, but a composite expression where Subscript is an operator without built-in meaning. You expect to do $x_1=2$ but you are actually doing Set[Subscript[x, 1], 2] which is to assign a Downvalue to the oprator Subscript and not an Ownvalue to an indexed x as you may intend. Read how to properly define indexed variables here – rhermans Jun 21 '18 at 13:56

Array[
(filehandle[#] = OpenAppend[StringTemplate["File.txt"][#]]) &
, 10];

?filehandle


Close /@ Array[filehandle, 10]


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