scs
scs

Reputation: 575

Unzipping file in R after download

I am trying to unzip a file after download using R. It unzips fine on Windows 10.

verbose <- T
zipdir <- file.path("downloads","zip")
datadir <- file.path("downloads","data")


if (!file.exists("downloads")) dir.create("downloads")
if (!file.exists(zipdir)) dir.create(zipdir)
if (!file.exists(datadir)) dir.create(datadir)


filename <- "On_Time_Reporting_Carrier_On_Time_Performance_1987_present_2019_2.zip"

fileurl <- str_c("https://transtats.bts.gov/PREZIP/",filename)

if (verbose == TRUE) print(str_c("File url: ",fileurl))

zipfile <- file.path(zipdir, filename)
if (verbose == TRUE) print(str_c("File: ",zipfile))

download.file(fileurl, zipfile)
unzip(zipfile)

Error 1 for a zip file means "operation not permitted"

Warning message:
In unzip(zipfile) : error 1 in extracting from zip file

Upvotes: 3

Views: 1087

Answers (1)

scs
scs

Reputation: 575

Here is the solution with the help of r2evans:

download.file(fileurl, zipfile, mode = wb)

unzip(zipfile, exdir=datadir, overwrite=TRUE)

Here comes the complete code to copy and try

verbose <- T
zipdir <- file.path("downloads","zip")
datadir <- file.path("downloads","data")


if (!file.exists("downloads")) dir.create("downloads")
if (!file.exists(zipdir)) dir.create(zipdir)
if (!file.exists(datadir)) dir.create(datadir)


filename <- "On_Time_Reporting_Carrier_On_Time_Performance_1987_present_2019_2.zip"

fileurl <- str_c("https://transtats.bts.gov/PREZIP/",filename)

if (verbose == TRUE) print(str_c("File url: ",fileurl))

zipfile <- file.path(zipdir, filename)
if (verbose == TRUE) print(str_c("File: ",zipfile))

#These are the modified lines in the code

#Mode = wb is required to download binary files

download.file(fileurl, zipfile, mode = wb)

#Changed the function so that it specifies the target directory
#I recommend overwrite=TRUE otherwise it might crash. Alternative would be to check with file.exists

unzip(zipfile, exdir=datadir, overwrite=TRUE)

Upvotes: 2

Related Questions