0

I searched and found stuff, but still having issues.

I have files in a directory "result (1).xlsx" and "result (2).xlsx". I want to change them to "new1.csv" and "new2.csv", etc.

I'm using the following and its not working (the problem seems to be regex.. and ive flip flopped between using just file.rename and sapply):

folder = "r:\\files"
files <- list.files(folder,pattern = "*.xlsx",full.names = T) 

sapply(files,FUN=function(eachPath){ 
    file.rename(from=eachPath,to= sub(pattern="result\\s(*).xlsx", 
paste0("new.csv"),eachPath))
})

Thanks

user136508
  • 49
  • 1
  • 5

2 Answers2

4

Before I answer this question, I'd like to mention that changing the extension of a file doesn't, in computer science, automatically change the file formatting. In other words, changing .xlsx to .csv for the purpose of converting it to a csv won't be what you want.

Instead, I'd recommend the readxl package to read xlsx files into R. Then once in R, you could save the table as a csv from there if you still needed. There are many ways to do this, here's one:

install.packages("readxl")

library(readxl)

df <- read_excel("yourData.xlsx")

#optional save/convert as csv
write.csv(df,"yourData.csv",row.names=FALSE)

If you'd like more info on how to do this more quickly over a series of files, take a look at the answers to this SO question on the topic.

www
  • 4,124
  • 1
  • 11
  • 22
1

Use instead

sapply(1:length(files),FUN=function(x){ 
     file.rename(from=files[x], to=paste0("new",x,".csv"))
})

If you still want to use regex, try this instead

sapply(files,FUN=function(eachPath){ 
     file.rename(from=eachPath, to=gsub(".+\\((\\d)\\)", "new\\1", eachPath))
})

If you want to change file formats rather than filename only, look into readxl and output using write.csv

CPak
  • 13,260
  • 3
  • 30
  • 48