【发布时间】:2022-01-05 06:33:13
【问题描述】:
作为 Google DA 证书分配的一部分,我试图找到一个关于如何使用 R 下载解压缩和合并多个 .csv 文件的优雅解决方案,但我一遍又一遍地面临同样的问题:
从 zip 文件中提取时出现错误 1
数据: 来源:Divvy
我运行的代码是:
## declare variable file names corresponding to calendar months
months <- c(202011:202012,202101:202110)
## declare directory for storing source files
storage <- "C:\\Users\\...\\start"
## vectors of all urls to download from and destination files
urls <-
paste0("https://divvy-tripdata.s3.amazonaws.com/",months, "-divvy-tripdata.zip")
## idea was to download archives into temporary files, unzip contents to 'storage' directory and remove tempdir.
temp <- tempdir()
tempfile <- paste0(temp,"\\",months,".zip")
##Downloading 12 months archives
for(i in seq(urls)){
download.file(urls[i],tempfile[i], mode="wb")
}
file_names <- list.files(temp, pattern = ".zip")
for (i in seq(file_names)){
unzip(file_names,exdir=storage,overwrite = FALSE)}
unzip("file_names", exdir = storage, overwrite = FALSE) 中的警告: 从 zip 文件中提取时出现错误 1
在解压缩步骤之前一切正常。所有档案都已下载,可以打开,文件没有损坏,属性显示扩展名为 .zip
我已经在不同目录中的多台机器上尝试了我的代码,尝试手动下载档案,尝试使用循环一次性解压缩每个人,ldply 仍然是相同的结果。
我花了 3 天时间试图解决它并感谢任何帮助:)
【问题讨论】:
-
忘记
file_names,这些毫无意义。你想要的是解压缩写入的临时文件,只需将seq替换为seq(tempfile)和unzip(tempfile[i], etc)。 -
非常感谢@RuiBarradas!如果可以的话,很少有澄清问题:所以问题真的是由于
file_names中没有路径,但只有名称?这意味着我不应该创建file_names,而是使用我的临时文件。但是后来我想知道为什么尽管将工作目录设置为tmpdir,但我的代码仍无法正常工作,据我了解,这会说从tmpdir解压缩带有file_names的文件? -
您没有将工作目录设置为
tmpdir,您创建了一个具有该名称的变量,仅此而已。是的,问题是由于文件名没有路径,unzip试图从 wd 中读取它们。