How to force Close of opened stream when stream write previously failed (bug in opening stream twice)?

I opened a stream like:

str = OpenWrite[NotebookDirectory[] <> "myStream.tsv"];


and made an error when writing the first line (meant to be the tsv headers):

WriteLine[strPrime, "Sampling_size", "Slope_fitted_model"]
// should have been:
WriteLine[strPrime, "Sampling_size\tSlope_fitted_model"]


I cannot close the stream now, nor overwrite it.

str
// str is now :
$Failed Close[str] // yield error: Close::stream:$Failed is not a string, SocketObject, InputStream[ ], or OutputStream[ ].


If I try overwrite :

str = OpenWrite[NotebookDirectory[] <> "myStream.tsv"];
// now yield error:
// OpenWrite::aofil: /myPath/myStream.tsv already open as /myPath/myStream.tsv.


I tried Delete[str], or str = Null ... not working either.

Can I force an open stream to close down?

EDITED

After comment I went to check again my question to replicate the error.

I found that opening the stream twice is sufficient to produce it.

How to replicate the error - is it a bug?

1.

strt = OpenWrite[NotebookDirectory[] <> "myStreamt.tsv"];


2. Now, run again the same line once it is already opened, you'll obtain this error:

OpenWrite::aofil:[..]/myStream.tsv already open as [..]/myStream.tsv.
OpenWrite::noopen: Cannot open [..]/myStream.tsv.


3.

Try to close the stream:

Close[strt]
// Close::stream: $Failed is not a string, SocketObject, InputStream[ ], or OutputStream[ ].  And strt variable is now: $Failed

I tried to Remove the variable (instead of Delete[])

Remove[strt]


It seems to nullify variables (they turn to blue color).

But when you try to openwrite again the stream with same variable, same error:

4.

strt = OpenWrite[NotebookDirectory[] <> "myStreamt.tsv"];
// OpenWrite::aofil:[..]/myStream.tsv already open as [..]/myStream.tsv.
// OpenWrite::noopen: Cannot open [..]/myStream.tsv.


Cannot using a new stream with a variable of previously corrupted one. Maybe trace is still pointing somewhere, from the void space ... :) Only way I found is to close the kernel.

Any solution to Clean out corrupted variables - close / reset broken streams ?

• You claim to have opened a file on a stream str, but you wrote to a stream strPrime. I looks to me that you should be closing strPrime. – m_goldberg Oct 15 '18 at 13:54
• hi @m_goldberg that was a typo - I opened a second stream after was having error, and mistaken when I was copy pasting here. – user305883 Oct 17 '18 at 8:02