# How can I use functions in file paths?

I'm very new to Mathematica and I'm trying to write into a file. I want to have a function in my file path. For Example:

s = OpenWrite["/Users/Home/Desktop/file[i].doc"]


Obviously in this format it will read it as it exactly appears above. How can I get it to open the file with the result for file[i]?

i.e. If file[i] = 1 then the program will compute:

s = OpenWrite["/Users/Home/Desktop/1.doc"]


Just another way, with Templates so only for V10+:

The following can be done without FileNameJoin but it is a good habit to use it:

file[i] = 1;

TemplateApply @ FileNameJoin[{\$HomeDirectory, "Desktop", "<*file[i]*>.doc"}]


...Desktop\1.doc

"<**>" is TemplateExpression

I'm sure this is a duplicate but to give you a quick answer here's a community wiki post:

Use ToString and StringJoin to form your argument:

file[i] = 1;

"/Users/Home/Desktop/" <> ToString @ file[i] <> ".doc"

"/Users/Home/Desktop/1.doc"


Also look at FileNameJoin.

At the risk of betraying how long I've been using Mathematica, the method I'm accustomed to uses StringForm[] (in conjunction with ToString[] since the output of that function, nonintuitively, is not a string):

file[i] = 1;

OpenWrite[ToString[StringForm["/Users/Home/Desktop/1.doc", file[i]]]]