0
$\begingroup$

WriteString["temp.txt","this string"] returns Null but creates an open stream which is reused if you again WriteString["temp.txt","this new string"]. How is this behavior more useful than the obvious alternative, which is to have a separate AppendString and to always close files after writing? The current approach seems bizarrely implicit to me. What is the motivation? Am I overlooking a convenience function that behaves as I expect? What is the expected approach to closing the opened stream in this case, since it is not returned? (I realize it is available via Streams[], but I assume that is not the answer.)

$\endgroup$
2
$\begingroup$

I can't speak to what the motivation might be, except to say explicit Open and Close calls for low-level file writing seem to be pretty common in the languages I've used.

If you only want to write a single thing and close it immediately, I would recommend using Export[].

If you want to use WriteString, you can just call Close["temp.txt"] and it will close it. You could even do:

file = "temp.txt";
WriteString[file, "this string"]
Close[file]

if you don't want to have to write your filename multiple times. Using Close[] does seem to be the expected method based on the documentation for WriteString[].

|improve this answer|||||
$\endgroup$
  • $\begingroup$ Is being able to close with the filename string guaranteed? I don't see it in the docs. $\endgroup$ – Alan Dec 3 '19 at 16:48
  • $\begingroup$ @Alan The documentation says: If there is only one stream with a particular name, the argument to Close can be "name". $\endgroup$ – Carl Woll Dec 3 '19 at 18:09
  • $\begingroup$ @CarlWoll Yes, I read that. It does not define how "name" is set. For example, it does not say that the "name" will be the string used as the first argument to WriteString. Is that guaranteed? $\endgroup$ – Alan Dec 3 '19 at 18:40

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.