'R - Rename files based on folder name and timestamps

I have N number of folders within a folder. For example, let's start with 2 folders for simplicity.

Folder iPhone, and Folder Android

Each folder would have 4 photos and with different timestamps. These timestamps define the sequence of the photos. And will be renamed simply by the alphabetical order.

Say the folders are at the following path

C:\Users\User1\Documents\myphonePhotos

So,

C:\Users\User1\Documents\myphonePhotos\iPhone C:\Users\User1\Documents\myphonePhotos\Android

Therefore the structure within iPhone folder is

iPhone
   -> Image 2022-04-05 at 1.34.30 PM.jpeg
   -> Image 2022-04-05 at 1.34.50 PM.jpeg
   -> Image 2022-04-05 at 1.34.55 PM.jpeg
   -> Image 2022-04-05 at 1.35.15 PM.jpeg

And the iPhone folder photos would then be renamed to

iPhone
   -> iPhone A.jpeg
   -> iPhone B.jpeg
   -> iPhone C.jpeg
   -> iPhone D.jpeg
r


Solution 1:[1]

This assumes you set the working directory to C:\Users\User1\Documents\myphonePhotos. I did this on a Mac so you may need to adjust paste0("./",dir,"/",files[n]) accordingly to account for the Windows directory structure.

#isolate the subdirectories
dirs <- list.dirs(full.names = FALSE)
dirs = dirs[-1]

#for loop over the directories
for (dir in dirs){
    #sort the files by the file name that includes date and time
    files <- list.files(dir)[order(list.files(dir))]
    #create subsitute names
    new_files <- paste0(dir, " ", LETTERS[1:length(files)], ".jpg")
   
    #for loop over the files in the directory
    for (n in 1:length(files)){
        file.rename(from = paste0("./",dir,"/",files[n]), to = paste0("./",dir,"/",new_files[n]))
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stomper