How to import a given csv located inside one of the files that are themselves inside a zip?

Viewed 54

Let's imagine a zip "a0" that contains 3 files "a01", "a02" and "a03". Using R, how to import a given csv (e.g. "ax.csv") that we don't know in which file is it?

NB : it is assumed that this given csv is unique in the entire zip, but that there may be other csv named differently.

Thanks for help

2 Answers

Use unzip. The first line gets the names of the files in the zip file. We then grep out the file we want. Change the pattern to whatever you are looking for. Finally the second unzip call extracts the csv file and we read it in. No packages are used.

nms <- unzip("test.zip", list = TRUE)$Name
csv_name <- grep("csv$", nms, value = TRUE)
if (length(csv_name) != 1) stop("cannot determine which file to extract")
unzip("test.zip", files = csv_name)
read.csv(csv_name)

If you are able to use bash, you could unzip outside R, grep and awk the filepath, and finally in R read.csv. Might be much faster.

x <- system("unzip -c baz.zip | grep 'foo.csv' | awk '{print $2}'", int=TRUE)
read.csv(unzip('baz.zip', x))
#               X  mpg cyl disp
# 1     Mazda RX4 21.0   6  160
# 2 Mazda RX4 Wag 21.0   6  160
# 3    Datsun 710 22.8   4  108

Data

system('mkdir dir1 dir2')
write.csv(mtcars[1:3, 1:3], './dir2/foo.csv')
write.csv(NULL, './dir1/bar.csv')
system('zip -r baz.zip dir1 dir2')
Related