readr icon indicating copy to clipboard operation
readr copied to clipboard

write_file cannot write files with ".zip" extension

Open MilesMcBain opened this issue 4 years ago • 4 comments

write_file cannot write .zip files. The issue seems to be in this switch statement in standardise_path: https://github.com/tidyverse/readr/blob/31236cf59a32173e47954e4be45ad44c6504695f/R/source.R#L161

Where the other zip functions create connections, readr::zipfile attempts to decompress the file file, which doesn't exist because we're trying to write it.

readr::write_file(charToRaw(letters), "./test.zip")
#> Error in utils::unzip(path, list = TRUE): zip file './test.zip' cannot be opened

Created on 2021-07-27 by the reprex package (v2.0.0)

MilesMcBain avatar Jul 27 '21 02:07 MilesMcBain

Base R does not support writing to zip files from a connection. e.g. there is no write equivalent to unz().

However you can now use the archive package to do this.

readr::write_file(paste0(letters, collapse = ""), archive::archive_write("letters.zip", "letters"))

jimhester avatar Aug 06 '21 17:08 jimhester

Ah sorry if I was unclear. I don't want to zip data. I have the raw data representing a zip file in the body of a http request. I can't write that to a .zip file on disk.

My work around was to write it with a different extension, then change the extension to zip after.

MilesMcBain avatar Aug 06 '21 21:08 MilesMcBain

My work around was to use:

readr:::write_file_raw_(x, connection)

I guess that is quite bad, because the unexported function could change or be removed in next release...

minemR avatar Sep 05 '23 11:09 minemR

Perhaps just use base::writeBin() or possibly brio::write_file_raw() if you want to write bytes to disk and not do any transformations of the data.

jimhester avatar Sep 14 '23 19:09 jimhester