我在 Windows 中有一个文件夹,其中包含 1000 个 ".dts" 格式的文件,例如 20170217.dts 。我想重命名所有文件的名称并将年份更改为 2019 ,例如 20190217.dts。我的目标是正确重命名文件夹中的所有文件,以便能够在其他软件中打开它们。我试过这个:
# define file path
filepath <- "C:/my file path/"
myfile_dts_2019 <- list.files(path = filepath , pattern =".dts")
# print
myfile_dts_2019
[1] "20172303.dts" "20172403.dts"
# replace 2017 with 2019
newfiles <- stringr::str_replace(myfile_dts_2019,"2017","2019")
newfiles
[1] "20192303.dts" "20192403.dts"
# try to rename on the folder
file.rename(myfile_dts_2019, newfiles)
[1] TRUE TRUE
我的脚本似乎在 R 中运行,但是文件夹中的原始文件的名称仍然以 2017 开头。我想知道如何在 Windows 文件夹中重命名它们。
最佳答案
list.files
具有默认的 full.names = FALSE
这意味着它只返回文件名,而不返回文件的路径。要重命名文件,我们需要完整路径,添加 full.names = TRUE
然后重命名。
myfile_dts_2019 <- list.files(path = filepath , pattern =".dts", full.names = TRUE)
关于使用 R 重命名 windows 文件夹中的多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55430699/