Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

If I initialise a stream as follows

OpenWrite["~/example"]

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
2  
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

4 Answers 4

up vote 4 down vote accepted

OpenWrite returns the stream it opens, so do this

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

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

 Close["~/example"]
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
2  
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

 
discard

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.