Home > database >  Rename files using a list
Rename files using a list

Time:03-30

I am trying to rename a list of files and saving them into a new folder. There is a large number of files and I need to set up a new structure, where some files from one folder will be split in several folders and some files from different folders will be put in one. So, I want to create an Excel template including the OLD filename and the NEW filename in two columns. This looks like this:

OLD NEW
C:/R/TEST/Test000.xlsx C:/R/TEST2/Test990.xlsx
C:/R/TEST/Test001.xlsx C:/R/TEST2/Test991.xlsx

I tried the following code:

filelist <- read.csv("test2.csv", sep = ";")

old_files <- filelist[,"OLD"]
new_files <- filelist[,"NEW"]

file.copy(from = old_files, to = new_files)

This however, returns the following error message:

Error in file.exists(from) : invalid 'file' argument

CodePudding user response:

You should use vectors in your file.copy command instead of columns. You can use the following code:

library(readxl)
filelist <- read_excel("data.xlsx")

old_files <- filelist[["OLD"]]
new_files <- filelist[["NEW"]]

This looks like this:

[1] "C:/R/TEST/Test000.xlsx" "C:/R/TEST/Test001.xlsx"
[1] "C:/R/TEST2/Test990.xlsx" "C:/R/TEST2/Test991.xlsx"

Finally use this:

file.copy(from = old_files, to = new_files)
  •  Tags:  
  • r
  • Related