【发布时间】:2019-06-18 11:26:50
【问题描述】:
我需要自动化 R 以将 csv 数据文件读取到 zip 文件中。
例如,我会输入:
read.zip(file = "myfile.zip")
在内部,要做的是:
- 解压
myfile.zip到一个临时文件夹 - 使用
read.csv读取其中包含的唯一文件
如果 zip 文件中有多个文件,则会引发错误。
我的问题是获取包含在 zip 文件中的文件名,以便提供它执行 read.csv 命令。有人知道怎么做吗?
更新
这是我根据@Paul 回答编写的函数:
read.zip <- function(zipfile, row.names=NULL, dec=".") {
# Create a name for the dir where we'll unzip
zipdir <- tempfile()
# Create the dir using that name
dir.create(zipdir)
# Unzip the file into the dir
unzip(zipfile, exdir=zipdir)
# Get the files into the dir
files <- list.files(zipdir)
# Throw an error if there's more than one
if(length(files)>1) stop("More than one data file inside zip")
# Get the full name of the file
file <- paste(zipdir, files[1], sep="/")
# Read the file
read.csv(file, row.names, dec)
}
由于我将在tempdir() 中处理更多文件,因此我在其中创建了一个新目录,因此我不会对这些文件感到困惑。我希望它可能有用!
【问题讨论】:
-
实际上第一个链接它不相关,因为我的问题不是解压缩文件,而是获取 zip 中文件的名称。但是,是的,第二个显示了
list.files命令,(到目前为止)我还不知道。 -
@jdanielnd:您可以使用
unzip(file, list=TRUE)获取 zip 文件中的文件名,正如我在回答中使用的那样。 -
这能回答你的问题吗? Extract certain files from .zip
标签: r compression