If I initialise a stream as follows


How do I close this stream? Close seems to expect a name, but I do not know the name of the stream in this format.

[edit] - Thanks for all the responses. It seems the simplest solution was

Close[<full path name to file>]

I had previously tried Close["~/example"] but to no avail.

  • 2
    $\begingroup$ Check Streams[] for it. When you use OpenWrite, you'd normally save the return value (the stream object), otherwise you can't use the stream at all. So under normal usage, this would not be a problem. $\endgroup$
    – Szabolcs
    Nov 22, 2013 at 21:53

4 Answers 4


OpenWrite returns the stream it opens, so do this

str = OpenWrite["~/example"]
OutputStream["/Users/oldmg/example", 83]

Also, all streams have a name. In this case it is "/Users/oldmg/example".


In the event you did not save the stream object for some reason, You should be able to close by the file name, ie. simply

  • $\begingroup$ Won't work. The stream name has "~" expanded to the full path. $\endgroup$
    – m_goldberg
    Nov 23, 2013 at 2:21
  • $\begingroup$ Use Close[FileNameJoin[{$HomeDirectory, "example"}]] instead. $\endgroup$
    – Michael E2
    Nov 23, 2013 at 3:34
  • 2
    $\begingroup$ You can also use Close[ExpandFileName["~/example"]]. $\endgroup$
    – Michael E2
    Nov 23, 2013 at 17:39

Typical usage:

(Write[#, "file contents"]; Close[#]) &@OpenWrite["test"];
(Print@Read[#]; Close[#]) &@OpenRead["test"];
file contents

The simplest, most general way to do this is probably via Streams[].

Set up some data ...

test = StringTake[ExampleData[{"Text", "DeclarationOfIndependence"}], 
   50] (* sample data ... *); 
str = StringToStream[#] & /@ 
  StringSplit[test]; (* converted to streams *)

Now the example ...

Streams[] (* all streams *)
ostr = Select[Streams[], SameQ[Head[#], InputStream] &] (* select inputStreamsonly *);
Close[#] & /@ ostr (* now close all the input streams ... *);
Streams[] (* only output streams remain*)
  • $\begingroup$ WithCleanup is a good tool for close the stream $\endgroup$
    – yode
    Aug 9, 2022 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.