在Stack Overflow上也有类似的问题,但没有一个完全满足我的特定需求.

我在工作目录的子文件夹中有一个具有随机名称的文件列表,例如working_directory/animals/photos

这些文件当前命名为:

Chicken.png
Moose.png
Cat.png

我想把它们重新命名为以下名称(我有5750张照片):

Animal1.png
Animal2.png
Animal3.png
...
Animal5750.png

我觉得应该有一个简单的解决方案,但我不太明白file.rename的编码来做到这一点,其中大多数示例是针对单个文件,或工作目录中的文件.

这是我从Stack Exchange上查看示例的try ,但这不起作用:

original_path <- 'animals/photos'
renamed_list <- dir(path = original_path, pattern = '*.png')

sapply(X = renamed_list, FUN = function(x) {
  file.rename(paste0(original_path, x),
              paste0(original_path, 'Animal', substring(x, first = 1))) }) 

先谢谢你

推荐答案

Here is a function that does what you ask for.
The main problem is to assemble the new names from the old names' path and file extension. This is done with functions

  • 包装base中的basenamedirname
  • 包装tools中的file_extfile_path_sans_ext.

连续的数字是由seq_along产生的.然后paste0sprintffile.path把所有的东西放在一起.

如果希望所有数字的位数相同,请将fmt_string字符串的格式部分更改为"%04d.%s".

file_rename_custom <- function(path, pattern, prefix = "Animals") {
  files_vec <- list.files(path = path, pattern = pattern, full.names = TRUE)
  ext <- tools::file_ext(files_vec)
  fname <- files_vec |>
    basename() |> 
    tools::file_path_sans_ext()
  
  fmt_string <- paste0(prefix, "%d.%s")
  new_name <- sprintf(fmt_string, seq_along(fname), ext)
  new_name <- file.path(dirname(files_vec), new_name)
  
  file.rename(files_vec, new_name)
}

working_directory <- getwd()
wd1 <- file.path(working_directory, "animals/photos")
wd2 <- file.path(working_directory, "animals")

dir(wd1)
# [1] "Cat.txt"    "Chiken.txt" "Moose.txt" 
file_rename_custom(wd1, "\\.txt")
# [1] TRUE TRUE TRUE
dir(wd1)
# [1] "Animals1.txt" "Animals2.txt" "Animals3.txt"

dir(wd2)
# [1] "Cat.txt"    "Chiken.txt" "Moose.txt"  "photos"    
file_rename_custom(wd2, "\\.txt")
# [1] TRUE TRUE TRUE
dir(wd2)
# [1] "Animals1.txt" "Animals2.txt" "Animals3.txt" "photos"

R相关问答推荐

将带有范围的字符串转换为R中的数字载体

如何使用geom_sf在边界显示两种 colored颜色 ?

单击 map 后,将坐标复制到剪贴板

如果行和大于值,则过滤

R根据条件进行累积更改

使用across,starts_with和ifelse语句变更多个变量

如何得到每四个元素向量R?

R中的时间序列(Ts)函数计数不正确

从多个线性回归模型中提取系数

给定开始日期和月份(数字),如何根据R中的开始日期和月数创建日期列

以NA为通配符的R中的FULL_JOIN以匹配其他数据中的任何值.Frame

根据列表中项目的名称合并数据框和列表

我如何go 掉盒子图底部的数字?

如何使用字符串从重复的模式中提取多个数字?

无法将条件case_when()应用于使用!!创建的新变量Mutations

从线的交点创建面

如何为包创建自定义roxygen2标签?

将日期列从字符转换为日期得到的结果是NAS

根据用户输入更改标记大小和 colored颜色 (R)

从多行中 Select 最小值