Copying files with the same name to a directory without overwriting (R!)

Asked

Viewed 109 times

3

Hello, I have a problem.

I have a dummy directory that contains a set of folders, each folder within itself contains a protocol folder, and within each folder I have one or more files. Ex:

  Pasta    Protocolo     Arquivo(s)
    A    ->    1     ->     x  
    B    ->    2     ->     y  
    C    ->    1     ->     z , x  

My challenge is to transfer the protocol folders to a new directory and put the files inside those folders without overwriting them. So the ideal result would be:

   Protocolo     Arquivo(s)
       1     ->     x (1) , x (2) , z  
       2     ->     y  

The folder and protocol are broken down into a df(test), so I’m creating these directories with a loop:

for (i in 1:3){ 
print(i)
  pasta_to <- paste("F:/", 
                    test$pasta[i], sep="/")

  # Cria o diretório se ele não existe

  ifelse(!dir.exists(pasta_to), 
         dir.create(pasta_to, recursive=TRUE), FALSE)

  pasta_from = paste("C:/Meus Documentos/destino", 
                     test$pasta_origem[i], 
                     test$pasta_do_anexo_resposta[i], 
                     sep="/")  

  files_from <- list.files(pasta_from)
  path_from <- paste(pasta_from, files_from, sep="/")
  file.copy(from=path_from, to = pasta_to, overwrite = F)
  } 

With this code he ends up overwriting the files with the same name x:

   Protocolo     Arquivo(s)
       1     ->     x  , z  
       2     ->     y  

How do I not overwrite files?

  • One remark: in the real case, I don’t know the name of the files, so I couldn’t use a ifelse(file exists.())

1 answer

1


Jessica, it’s all right?

It’s not that the file.copy() ends up overwriting the entries with the same name. On the contrary, it does NOT overwrite files with the same name, since you have set overwrite = F.

A possible solution, however laborious, is to create a function that compares the file list of the source folder with the file list of the destination folder. If there are acquisitions with the same name, change the name, for example put a suffix to differentiate. Then yes, after that run the file.copy().

Let’s go for the solution:

# Definindo as pastas de origem e destino
path_origem <- "C:/origem"
path_destino <- "C:/destino"

# Função que verifica se existe algum arquivo com o mesmo nome entre as duas listas
verifica.repetido <- function(origem, destino) {
  if(length(setdiff(lista_origem, lista_destino)) != length(origem)) {
    return(TRUE)
  } else {
    return(FALSE)
  }
}

# Função que adiciona "#" no nome do arquivo de origem, para diferenciar do de destino
renomeia <- function(origem, destino, path_origem) {
  for (i in 1:length(origem)) {
    for (j in 1:length(destino)) {
      if (origem[i] == destino[j]) {
        novo_nome = gsub("\\.", "#.", origem[i])
        file.rename(from = paste(path_origem, origem[i], sep = "/"),
                    to = paste(path_origem, novo_nome, sep = "/"))
      }
    }
  }
  return(origem)
}

# Obtendo a lista de arquivos das pastas de origem e destino
lista_origem <- list.files(path_origem)
lista_destino <- list.files(path_destino)

# Verificando se há algum nome repetido entre as listas
repetido <- verifica.repetido(lista_origem, lista_destino)

# Se houver repetido, o laço abaixo executa até que não haja mais nenhum repetido
repeat{
  renomeia(lista_origem, lista_destino, path_origem)
  lista_origem <- list.files(path_origem)
  repetido <- verifica.repetido(lista_origem, lista_destino)
  if(!repetido) {
      break
    }
}

# Incluindo o caminho completo da pasta de origem
lista_origem <- list.files(path_origem, full.names = T)

# Colando os arquivos de origem na pasta de destino
file.copy(from = lista_origem, to = path_destino)

I’m sure there is a less laborious way, but anyway, this way it is possible to paste as many times as necessary, in the destination folder, files with existing names. The only thing that will happen is to add the # character at the end of the file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.