首页 > 解决方案 > 使用R解压缩包含相同名称的多个文件

问题描述

我在一个文件夹中有 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)

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

无论如何,是否可以通过重命名它们或在提取时为文件名添加前缀/后缀来保存它们中的每一个?

标签: rdataframerstudiounzip

解决方案


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

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

}

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


推荐阅读