尝试使用 R 从一个文件夹创建 zip 文件。
这里提到了“Rcompression”包: 从文件夹创建 zip 文件
但是我没有找到在哪里可以下载Windows系统的这个包。
有什么建议吗?或其他函数来创建 zip 文件?
您可以使用
zip
包中的 utils
功能轻松创建 zip 文件。假设您有一个目录 testDir
并且您希望在该目录中压缩一个文件(或多个文件),
dir('testDir')
# [1] "cats.csv" "test.csv" "txt.txt"
zip(zipfile = 'testZip', files = 'testDir/test.csv')
# adding: testDir/test.csv (deflated 68%)
压缩文件保存在当前工作目录中,除非在
zipfile
参数中指定了不同的路径。 我们可以使用 查看它相对于原始解压文件的大小
file.info(c('testZip.zip', 'testDir/test.csv'))['size']
# size
# testZip.zip 805
# testDir/test.csv 1493
您可以使用
压缩整个文件目录(如果没有子文件夹)files2zip <- dir('testDir', full.names = TRUE)
zip(zipfile = 'testZip', files = files2zip)
# updating: testDir/test.csv (deflated 68%)
# updating: testDir/cats.csv (deflated 27%)
# updating: testDir/txt.txt (stored 0%)
和
unzip
查看文件,
unzip('testZip.zip', list = TRUE)
# Name Length Date
# 1 testDir/test.csv 1493 2014-05-14 20:54:00
# 2 testDir/cats.csv 116 2014-05-14 20:54:00
# 3 testDir/txt.txt 32 2014-05-08 09:37:00
注意: 来自
?zip
,关于 zip
论证。
在 Windows 上,默认依赖于路径中的 zip 程序(例如来自 Rtools 的程序)。
为了避免 (a) 相对路径的问题(即 zip 文件本身包含一个带有要压缩的完整文件夹路径的文件夹结构)和 (b)
for
循环(好吧,样式),您可以使用
my_wd <- getwd() # save your current working directory path
dest_path <- "C:/.../folder_with_files_to_be_zipped"
setwd(dest_path)
files <- list.files(dest_path)
named <- paste0(files,".zip")
mapply(zip, zipfile = named, files = files)
setwd(my_wd) # reset working directory path
与 R 的内置
unzip
功能不同,zip
需要 7-zip (Windows) 等 zip 程序或 Rtools 的一部分存在于系统路径中。
对于仍在寻找此内容的人:现在有一个不依赖于外部可执行文件的“zip”包。
值得注意的是,如果找不到 zip 程序,
zip()
将默默失败。
zip
返回错误代码(或退出代码)不可见。也就是说,它不会打印,除非您明确要求它打印。
您可以运行
print(zip(output, input))
来打印退出代码,在没有找到 zip 程序的情况下,将打印 127
或者你可以按照以下方式做一些事情
#exit code 0 for success, all other codes are for failure
if (exit_code <- zip(output, input) != 0) {
stop("Zipping ", input, " failed with exit code:", exit_code)
}
您可以从
omegahat
存储库安装:
install.packages('Rcompression', repos = "http://www.omegahat.org/R", type = "source")
对于 Windows,您需要跳过安装 zlib 和 bzip2 并进行适当链接的步骤。
在某些情况下可以使用utils::zip
。它有很多问题。一种情况是,对于 Windows,您可以在命令提示符下使用的字符串的最大长度为 8191 个字符(某些版本上为 2047 个字符)。如果您压缩的目录包含大量目录/文件名称字符,这将导致问题。例如,如果您压缩 Firefox 配置文件目录。我还发现需要相对于我正在压缩的目录发出 zip 命令才能使用相对目录名称。 Rcompression
有一个 altNames
参数来处理这个问题。
话虽这么说,我一直在让 Rcompression
在 Windows 上运行时遇到问题。
做到这一点
#Convertir todas las carpetas en .zip
d <- "C:/Users/Eric/Documents/R/win-library/3.3"
array <- list.files(d)
for (i in 1:length(array)){
name <- paste0(array[i],".zip")
zip(name, files = paste0(d,paste0("/",array[i])))
}