使用 R 将大量文件组织到文件夹中?

Organising large number of files into folders using R?

对于问题的简单性表示歉意,因为我是 R 的新手。

我有大量1分钟的音频文件,每5分钟录制1分钟。我需要将它们按小时整理并保存到一个新文件夹中,因此每 12 个文件需要保存到一个新文件夹中。我有 7472 个这样的文件,所以手动执行此操作会花费太长时间。

以下是文件名示例:

20210111_000500.wav,
20210111_001000.wav,
20210111_001500.wav,
20210111_002000.wav,
20210111_002500.wav,
20210111_003000.wav,
20210111_003500.wav,
20210111_004000.wav,
20210111_004500.wav,
20210111_005000.wav,
20210111_005500.wav,

我希望所有内容都在一个文件夹中,下一个小时开始于 20210111_010000.wav 等等。

我该怎么做?

非常感谢任何帮助,谢谢!

您可以按照这些思路进行尝试。我首先找到所有.wav文件,然后定义文件夹,创建文件夹,最后将.wav文件移动到新文件夹。

library(tidyverse)

setwd("path_where_wav_files_are_located_goes_here")

# a vector of paths to all .wav files in the specified directory
original_paths <- dir(pattern=".WAV$", full.names = T) %>% str_replace("\.", getwd())
# only the file names
file_names <- dir(pattern=".WAV$")

# creating a data.frame with original paths and new paths where files are to be moved
df <- tibble(original_paths, file_names) %>%
  mutate(
    folder_name = (row_number() %/% 12 + 1) %>% paste0("_", .), # using integer division so that i have a dedicated folder for each 12 files
    new_path = paste0(getwd(), "/", folder_name, "/", file_names)
  )

# creating the directories
df$folder_name %>%
  unique() %>%
  paste0(getwd(), "/",  .) %>%
  map(
    ~dir.create(.x)
  )

# moving the files
walk2(df$original_paths, df$new_path, ~file.rename(.x, .y))

你可以按照以下方式做一些事情:

nms <- list.files(pattern = "\.wav", full.names = TRUE)
groups <- split(nms, format(strptime(nms, "%Y%m%d_%H%M%S"),"%Y%m%d_hour_%H"))

f <- function(x, y, folder = "my_folder"){
  if(!die.exists(folder)){
      fl <- dir.create(folder)
      stopifnot(fl)
   }
  new_dir <- file.path(folder, y)
  if(!dir.exists(new_dir)) dir.create(new_dir)
  file.copy(x, file.path(new_dir, basename(x)))
  file.remove(x)
}

Map(f, groups, names(groups))