How to extract a file in a zip archive (without using OS specific tools)?

,

Thank you all.

I ended up writing the following function:

unzip(file,exdir=“”)

Unzip a zipped archive using ZipFile

Arguments

  • file: a zip archive to unzip and extract (absolure or relative path)
  • exdir="": an optional directory to specify the root of the folder where to extract the archive (absolute or relative).

Notes:

  • The function doesn’t perform a check to see if all the zipped files have a common root.

Examples

julia> unzip("myarchive.zip",exdir="mydata")
function unzip(file,exdir="")
    fileFullPath = isabspath(file) ?  file : joinpath(pwd(),file)
    basePath = dirname(fileFullPath)
    outPath = (exdir == "" ? basePath : (isabspath(exdir) ? exdir : joinpath(pwd(),exdir)))
    isdir(outPath) ? "" : mkdir(outPath)
    zarchive = ZipFile.Reader(fileFullPath)
    for f in zarchive.files
        fullFilePath = joinpath(outPath,f.name)
        if (endswith(f.name,"/") || endswith(f.name,"\\"))
            mkdir(fullFilePath)
        else
            write(fullFilePath, read(f))
        end
    end
    close(zarchive)
end

If one is interested, I added it to my own repository of utility functions (GitHub - sylvaticus/LAJuliaUtils.jl: Utility functions for Julia, mainly dataframes operations)

9 Likes