1
$\begingroup$

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"]
$\endgroup$
5
$\begingroup$

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

$\endgroup$
3
$\begingroup$

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.

$\endgroup$
2
$\begingroup$

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]]]]
$\endgroup$

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.