# Safe way to open new file and unlock an existing file to enable deletion, if it exists

**URL:** <https://discourse.julialang.org/t/safe-way-to-open-new-file-and-unlock-an-existing-file-to-enable-deletion-if-it-exists/88676>\
**Category:** New to Julia\
**Tags:** filesystem, io, file\
**Created:** [October 13, 2022, 4:12pm UTC](https://discourse.julialang.org/t/safe-way-to-open-new-file-and-unlock-an-existing-file-to-enable-deletion-if-it-exists/88676 "2022-10-13T16:12:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ellocco](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ellocco/32/31331_2.png) [@ellocco](https://discourse.julialang.org/u/ellocco)\
**Post date:** [October 13, 2022, 4:12pm UTC](https://discourse.julialang.org/t/safe-way-to-open-new-file-and-unlock-an-existing-file-to-enable-deletion-if-it-exists/88676/1 "2022-10-13T16:12:54Z")

</div>

Assume you have the habit to use the variable `fid` as an `IOStream`-variable and you are not sure, if the related file is still open (it might be that a process has crashed or you have forgotten to close the old not longer used `IOStream` properly), how could you reuse this file name without a restart of Julia?  
Here my proposal:

```julia
function MyLibOpenTxtIOStream(_fn::AbstractString, _fid::String, _openTxtIOStream::Bool=true)
    getvars() = [string(v) for v in sort!(names(Main)) if isdefined(Main, v) && !(v in (:Base, :Main, :Core, :InteractiveUtils, :ans))]
    if ispath(_fn)
        if any(occursin.(_fid, getvars()))
            _s = Symbol(_fid)
            if @eval(Base.@isdefined($_s))
                if @eval(isa($_s, IOStream))
                    @eval(close($_s))
                    GC.gc() # garbage collection
                end
            end
        end  
        rm(_fn, force = true)
    end  
    _dir, _ = splitdir(_fn)
    if ispath(_dir)
        if _openTxtIOStream
            return open(_fn, "w")
        else    
            return missing
        end
    else
        error("Path does not exist!")
    end
end

fid = open_new_IOStream("/tmp/file.txt", "fid")

```

Now my question: Is this code somehow fishy?

Remark:  
The `getvars()` is taken from: [Recommended way to delete user-defined variables](https://discourse.julialang.org/t/recommended-way-to-delete-user-defined-variables/56209/3)
