Skip to content

Support do statement syntax #93

@the-noble-argon

Description

@the-noble-argon

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions