rename file with date format

Can some one please advise that how to rename file name with date format.
I have below file and want to rename date with current date .

ex: support data 05122019.xlsx

i want to create file like below
support data 31032019.xlsx

Are you looking for something like this?

df <- iris

write.csv(x = df,
          file = "try_iris 01012019.csv")

list.files()
#> [1] "reprex_reprex.R"        "reprex_reprex.spin.R"  
#> [3] "reprex_reprex.spin.Rmd" "try_iris 01012019.csv"

file.rename(from = "try_iris 01012019.csv",
            to = paste(gsub(pattern = "\\d|.csv",
                            replacement = "",
                            x = "try_iris 01012019.csv"),
                       format(x = Sys.Date(),
                              format = "%d%m%Y"), 
                       ".csv",
                       sep = "",
                       collapse = ""))
#> [1] TRUE

list.files()
#> [1] "reprex_reprex.R"        "reprex_reprex.spin.R"  
#> [3] "reprex_reprex.spin.Rmd" "try_iris 31032019.csv"

Created on 2019-03-31 by the reprex package (v0.2.1)

I've done with .csv, you can change it to .xlsx easily.

1 Like

Here's a way to do it for xlsx file.
Please check how to use the openxlsx library for more details.

wb <- openxlsx::loadWorkbook(File Name)
openxlsx::saveWorkbook (wb,paste0("support data ",Sys.Date()), overwrite = T)

Hi Anshuman, welcome to the community!

The method you suggested above is indeed a good one, but it doesn't really rename the file. It creates another copy of the file with a name of your choice. See below:

# creating dummy data
openxlsx::write.xlsx(x = iris,
                     file = "try_iris 01012019.xlsx")
#> Note: zip::zip() is deprecated, please use zip::zipr() instead

# name of files in working directory before
list.files()
#> [1] "reprex_reprex.R"        "reprex_reprex.spin.R"  
#> [3] "reprex_reprex.spin.Rmd" "try_iris 01012019.xlsx"

# what you (@anshuman_k) suggested
openxlsx::saveWorkbook(wb = openxlsx::loadWorkbook(file = "try_iris 01012019.xlsx"),
                       file = paste0(gsub(pattern = "\\d|.xlsx",
                                          replacement = "",
                                          x = "try_iris 01012019.xlsx"),
                                     format(x = Sys.Date(),
                                            format = "%d%m%Y"), 
                                     ".xlsx"))

# name of files in working directory after
list.files()
#> [1] "reprex_reprex.R"        "reprex_reprex.spin.R"  
#> [3] "reprex_reprex.spin.Rmd" "try_iris 01012019.xlsx"
#> [5] "try_iris 01042019.xlsx"

Created on 2019-04-01 by the reprex package (v0.2.1)

Yeah I do agree.
It will work when the file, one is working is same as the new to be created (updated).

This topic was automatically closed 21 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.