Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support do statement syntax #93

Open
the-noble-argon opened this issue Oct 4, 2022 · 0 comments
Open

Support do statement syntax #93

the-noble-argon opened this issue Oct 4, 2022 · 0 comments

Comments

@the-noble-argon
Copy link

While using this package, I wasn't able to find any do statement syntax which is useful for closing open files if there was an error. The "do" statement on "open" is a common pattern to write data to a file handle that fails gracefully:

open("outfile", "w") do fh
    write(fh, data)
end

It would be nice if we could do something like this (which I use to break up a DataFrame into timestamp-value CSV files and zip them)

function split_zip(fname::String, data::DataFrame)
    zip_build(fname) do zh #zip handle
        for col in propertynames(data)[(begin+1):end]
            subname = string(col)*".csv"
            zip_into(zh, subname) do fh #file handle
                newDf = DataFrame(timestamp=data[!,:TimeStamp], value=data[!,col])
                CSV.write(fh, newDf)
            end
        end
    end
end

In order to enable this standard behavior, I defined the following functions to work similar to "open"

function zip_build(f::Function, fname::String)
    zipfile = ZipFile.Writer(fname)
    try
        return f(zipfile)
    finally
        close(zipfile)
    end
end

function zip_into(f::Function, zhandle::ZipFile.Writer, subname::String)
    zipsub = ZipFile.addfile(zhandle, subname)
    try
       return f(zipsub)
    finally
        close(zipsub)
    end
end

Anyone who reads this can implement this behaviour themselves, but it would be nice if this (or something similar) could make its way into a future release. It saves me the headache of dealing with open files and permissions issues if something breaks halfway through writing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant