EOFError when extracting from a ZipFile inside a function

I am trying to download a Zip file and extract a few files. When I run this code outside of a function, it works great. However, when wrapped in a function I get an EOFError.

I’ve included the two versions below. Any advice would be immensely appreciated.

Non Function Version - Works

using Downloads
using ZipFile


data = (
    summary_make = "IOMake_After_Redefinitions_PRO_1997-2023_Summary.xlsx",
    summary_use = "IOUse_After_Redefinitions_PRO_1997-2023_Summary.xlsx",
    detailed_make = "IOMake_After_Redefinitions_2017_Detail.xlsx",
    detailed_use = "IOUse_After_Redefinitions_PRO_2017_Detail.xlsx",
)

output_path = "data/national"

# Public link, no API key required
url = "https://apps.bea.gov/industry/iTables%20Static%20Files/AllTablesIO.zip"


X = Downloads.download(url, "tmp.zip")
r = ZipFile.Reader(X)


if !isdir(output_path)
    mkpath(output_path)
end

for f in r.files
    file_name = replace(f.name, " "=>"") #the bea file names may have random spaces
    if file_name∈data
        write(joinpath(output_path,file_name),read(f))
    end
end

close(r)
rm(X)

Function Version - Throws error

function fetch_zip_data(
    url::String,
    data;
    output_path::String = joinpath(pwd(), "data"),
)
    if !isdir(output_path)
        mkpath(output_path)
    end

    X = Downloads.download(url, "tmp.zip")
    r = ZipFile.Reader(X)

    for f in r.files
        file_name = replace(f.name, " "=>"")
        if file_name∈data
            write(joinpath(output_path,file_name),read(f))
        end
    end
    close(r)
    rm(X)
    return true
end

fetch_zip_data(url, data)

It looks like you have a typo where fetch_zip_file(url, data) should be fetch_zip_data(url, data)

This is true, it’s what happens when you change the function name when asking a question and then don’t run the code locally to test.

I’ll fix that error, but the end of file error is still present.

What is the output of

import Pkg
Pkg.status(Pkg.PKGMODE_MANIFEST)

and

versioninfo()

?
The function works for me.

Good news, it works for me now too. :expressionless:

I think the issue was order of operations related, I tested the non-function version and that kept a lock on the file, or something.

Thank you for testing this for me. I’m am very relieved that the fix was incredibly easy, and the error was totally my fault.

Also, you might want to add some extra check that none of the names in data are absolute paths or other weird things, otherwise write(joinpath(output_path,file_name), ... may overwrite some important file on your computer.