【问题标题】:Unzip Multiple files containing same name using R使用R解压缩包含相同名称的多个文件
【发布时间】:2019-03-16 18:09:38
【问题描述】:

我在一个文件夹中有 105 个压缩文件。它们都包含一个 csv 文件,每个文件都具有相同的名称,即“EapTransactions_1”

目前我在 R 中使用以下代码将它们全部提取到一个新文件夹中:

library(plyr)    
outDir<-"C:/Users/dhritul.gupta/Migration Files/Trial1/extract"
zipF=list.files(path = "C:/Users/dhritul.gupta/Migration Files/Trial1", pattern = "*.zip", full.names = TRUE)
ldply(.data = zipF, .fun = unzip, exdir = outDir)

这种方法的问题在于,由于所有文件名都相同,因此每个文件都会被覆盖,并且只保存最后一个。

是否可以通过重命名或在提取时为文件名添加前缀/后缀来保存每个文件?

【问题讨论】:

    标签: r dataframe rstudio unzip


    【解决方案1】:

    您可以尝试使用file.rename 在每个文件的末尾添加一个唯一编号,然后再拨打使用unzip 的电话:

    zipF <- list.files(path = "C:/Users/dhritul.gupta/Migration Files/Trial1",
        pattern = "*.zip", full.names = TRUE)
    file.rename(zipF, paste0("EapTransactions_", 1:105))
    ldply(.data=zipF, .fun=unzip, exdir=outDir)
    

    【讨论】:

    • 不幸的是,这会引发错误 - file.rename(zipF, paste0("EapTransactions_", 1:105)) 中的错误:'from' 和 'to' 的长度不同
    • I have a 105 zipped files in a folder ...看起来你没有,但如果你告诉我们你实际上有多少个文件,我们可以修复上面的代码。
    • 翻译:错误消息是说您没有文件夹中有 105 个文件,而是您有一些其他数字。请告诉我们您实际拥有多少个文件。
    • 你是对的。很抱歉,文件夹中只有 104 个文件。但是当我更改代码时,我在下一行出现以下错误: > ldply(.data = zipF, .fun = unzip, exdir = outDir) quickdf(unname(split(vec, rep(seq_len(ncol), nrow)))) : length(rows) == 1 is not TRUE 另外:有 50 个或更多警告(使用 warnings() 查看前 50 个)
    • 我不知道你为什么会收到这个错误。检查以确保文件确实存在。也许尝试让它只使用一个 ZIP 文件,然后从那里构建。
    【解决方案2】:

    我尝试根据蒂姆的想法构建一些东西。当我将文件存储在临时位置以重命名文件时,它对我有用。然后我将重命名的文件移动到最终目的地并删除了临时文件。

    TempoutDir <-"C:/Users/dhritul.gupta/Migration Files/Trial1/extract/Temp" # Define a temp location
    
    setwd(TempoutDir) #setwd for rename/remove functions to work
    
    for (i in 1:length(zipF))
    {
      unzip(zipF[i],exdir=TempoutDir,overwrite = FALSE)  
    
      #Files are overwritten because of same name. Give a new name to the file with a random number using runif and save them at the final location. Delete the files in temp folder
    
      a <- c(list.files(TempoutDir)) #Vector with actual file name
    
      b <- c(paste(runif(length(list.files(TempoutDir)), min=0, max=1000 ),as.character(list.files(TempoutDir))))
      #Vector with an appended temp number in front of the file name
    
      file.rename(a,b) # Rename the file in temp location
      file.copy(list.files(TempoutDir),outDir) # Move file from temp location to main location
      file.remove(list.files(TempoutDir)) # Delete files in Temp location
      rm(a)
      rm(b) #Delete vectors a,b from environment
    
    }
    
    

    您应该将所有文件移动到所需文件夹,并在文件名前附加随机数字,并且临时文件夹中没有任何内容

    【讨论】:

      猜你喜欢
      • 2010-12-06
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      相关资源
      最近更新 更多