# is the behavior of WriteString surprising?

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.)

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[].

• Is being able to close with the filename string guaranteed? I don't see it in the docs. – Alan Dec 3 '19 at 16:48
• @Alan The documentation says: If there is only one stream with a particular name, the argument to Close can be "name".  – Carl Woll Dec 3 '19 at 18:09
• @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? – Alan Dec 3 '19 at 18:40