Zip folder using Julia

Hi!
How to zip an entire folder using Julia?
I tried using ZipFile with no success.
Thanks.

any reason you need to do this ā€œusing Juliaā€? you can just use zip command line, you can let julia run that command.

1 Like

I was trying to use pure Julia. Currently, I am running a shell command.

again, Iā€™m curious WHY is ā€œpureā€ Julia important for this usage. I mean the zlib that Julia uses in stdlib is not written in Julia.

1 Like

There are use-cases where zipping inside Julia is useful, because many ā€œdata formatsā€ are basically only some zipped files. Exporting such formats from Julia need a working zipping-tool.

Using the commandline relies on some pre-installed software, which is at least not platform independent.
(I think ZipFile is also only just a C-code-wrapper, but at least the external dependecies are resolved on the system when installing the Julia library).

I am struggling with this, too. The closest I currently have works only if there are no sub-directories inside the folder to pack:

function zip(tar_file, src_dir)
    zdir = ZipFile.Writer(tar_file) 
    for (root, dirs, files) in walkdir(src_dir)
        for file in files
            filepath = joinpath(root, file)
            f = open(filepath, "r")
            content = read(f, String)
            close(f)
            zf = ZipFile.addfile(zdir, basename(filepath));
            write(zf, content)
        end
    end
    close(zdir)
end
1 Like

Maybe create a tar file of the folder (https://github.com/JuliaIO/Tar.jl) and then zip the tar file?

5 Likes

Thanks, didnā€™t know that one!
But sometimes it is explicitly needed to export a *.zip, so it would be usefull to have a solution for this, too.

2 Likes

Just take out the ā€œbasenameā€. The only way zip files record directory structure is by recording the full relative path name.

Well, you might need to do something special on Windows and normalize the path separator to ā€˜/ā€™. (Donā€™t have easy access, so canā€™t test.)

1 Like

Exactly, this was working for me too.

zipfile = "[path to my ZIP file].zip"
comprDir = "[path you want to zip]"
compress = true # or false, like you wish
zdir = ZipFile.Writer(zipfile) 
for (root, dirs, files) in walkdir(comprDir)
    for file in files
        filepath = joinpath(root, file)
        f = open(filepath, "r")
        content = read(f, String)
        close(f)

        zippath = subtractPath(filepath, comprDir * "/")
        println("\t$(zippath)")
        zf = ZipFile.addfile(zdir, zippath; method=(compress ? ZipFile.Deflate : ZipFile.Store));
        write(zf, content)
    end
end
close(zdir)
1 Like