Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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. – Szabolcs Nov 22 '13 at 21:53
up vote 4 down vote accepted

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

share|improve this answer

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

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

Typical usage:

(Write[#, "file contents"]; Close[#]) &@OpenWrite["test"];
(Print@Read[#]; Close[#]) &@OpenRead["test"];
file contents
share|improve this answer

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*)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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