writexl::write_xlsx() stop overwriting and get a message

How do I stop writing an excel file if the file already exists and instead get a message?

For example, if the mtcars-data.xlsx file already exists in the data folder, I do not want to run the following code. Instead, I would like to have this message "mtcars-data.xlsx already exists".

library(writexl)
df <- mtcars
writexl::write_xlsx(df, "data/mtcars-data.xlsx")

You could write a function like the following. I used write.csv() since I do not have the writexl package.

MyWrite <- function(Obj, Name) {
  if (file.exists(Name)) {
    message(paste(Name, "already exists!"))
  } else {
    write.csv(Obj, Name)
  }
  
}
1 Like

@FJCC Many thanks! It works perfectly :smiley:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.