Mathematica: exporting to a variable path
this is tricky. Once the path to export data in Mathematica is under quotes, how can I insert a variable as part of the path? In other word开发者_运维技巧s, I'm inside a loop that increments VAL and want to export MyData to VAL.dat. Ideas?
Pseudocode: Export["~/Documents/VAL", MyData]
In addition to Howard and Mr.Wizard's answers I could say that it would be good to look up FileNameJoin
for a nice, system-independent way to compose path strings and IntegerString
which you could use to convert integers to strings with a fixed number of positions, making your files sort more nicely:
In[33]:= VAL = 32;
IntegerString[VAL, 10, 4]
Out[34]= "0032"
I usually don't have much need for inter-OS compatibility (programming mostly for myself), so my usual style would be something like
Export["directoryPart\\FixedFileNamePart"<>IntegerString[VAL, 10, 4]<>".dat","TSV"]
Replace "TSV" with the file type you need if it isn't clear from the extension. Please note that I am on windows, which uses the backslash as separator. Since this is also the escape character, it has to be escaped with a backslash itself; this explains the double backslash. You seem to be on a UNIX derivate so there's no need for that. This does show the value of FileNameJoin
which takes care of these details automatically.
How about converting your number to string and join it with the path:
"~/Documents/"<>ToString[VAL]
In direct answer to your question, you can use StringReplace
:
Table[
StringReplace[
"~/Documents/#.dat",
"#" :> IntegerString[VAL, 10, 4]],
{VAL, 27, 29}
]
{"~/Documents/0027.dat", "~/Documents/0028.dat", "~/Documents/0029.dat"}
"#" was arbitrarily chosen as a placeholder. Another character or string of characters could be used just as well.
精彩评论