Home > database >  How to rename files in reverse order in Python?
How to rename files in reverse order in Python?

Time:02-22

I have a scanner that creates a folder of images named like this:

A1.jpg A2.jpg A3.jpg B1.jpg B2.jpg B3.jpg etc

There are hundreds of images and I would like to rename by reversing the order:

B3.jpg → A1.jpg
B2.jpg → A2.jpg
B1.jpg → A3.jpg
...

The closest example I can find is in shell but that is not really what I want:

for i in {1..50}; do
    mv "$i.txt" "renamed/$(( 50 - $i   1 )).txt"
done

Perhaps I need to save the filenames into a list (natsort maybe?) then use those names somehow?

I also thought I could use the image creation time as the scanner always creates the files in the same order with the same names. In saying that, any solutions may not be so useful for others with the same challenge.

What is a sensible approach to this problem?

CodePudding user response:

I would store the original list. Then rename all files in the same order (e.g. 1.jpg, 2.jpg etc.). Then I'd rename all of those files into the reverse of the original list.

In that way you will not encounter duplicate file names during the renaming.

You can make use of the pathlib functions rename and iterdir for this. I think it's straightforward how to put that together.

CodePudding user response:

I don't know if this is the most optimal way of doing that, but here it is:

import os

folder_name = "test"
new_folder_name = folder_name   "_new"

file_names = os.listdir(folder_name)
file_names_new = file_names[::-1]
print(file_names)
print(file_names_new)

os.mkdir(new_folder_name)

for name, new_name in zip(file_names, file_names_new):
    os.rename(folder_name   "/"   name, new_folder_name   "/"   new_name)

os.rmdir(folder_name)
os.rename(new_folder_name, folder_name)

This assumes that you have files saved in the directory "test"

CodePudding user response:

Solution based on shutil package (os package sometimes has permissions problems) and "in place" not to waste memory if the folder is huge

import wizzi_utils as wu
import os


def reverse_names(dir_path: str, temp_file_suffix: str = '.temp_unique_suffix') -> None:
    """
    "in place" solution:
        go over the list from both directions and swap names
        swap needs a temp variable so move first file to target name with 'temp_file_suffix'
    """
    files_full_paths = wu.find_files_in_folder(dir_path=dir_path, file_suffix='', ack=True, tabs=0)
    files_num = len(files_full_paths)

    for i in range(files_num):  # works for even and odd files_num
        j = files_num - i - 1
        if i >= j:  # crossed the middle - done
            break
        file_a, file_b = files_full_paths[i], files_full_paths[j]
        print('replacing {}(idx in dir {}) with {}(idx in dir {}):'.format(
            os.path.basename(file_a), i, os.path.basename(file_b), j))
        temp_file_name = '{}{}'.format(file_b, temp_file_suffix)
        wu.move_file(file_src=file_a, file_dst=temp_file_name, ack=True, tabs=1)
        wu.move_file(file_src=file_b, file_dst=file_a, ack=True, tabs=1)
        wu.move_file(file_src=temp_file_name, file_dst=file_b, ack=True, tabs=1)
    return


def main():
    reverse_names(dir_path='./scanner_files', temp_file_suffix='.temp_unique_suffix')
    return


if __name__ == '__main__':
    main()

found 6 files that ends with  in folder "D:\workspace\2021wizzi_utils\temp\StackOverFlow\scanner_files":
    ['A1.jpg', 'A2.jpg', 'A3.jpg', 'B1.jpg', 'B2.jpg', 'B3.jpg']
replacing A1.jpg(idx in dir 0) with B3.jpg(idx in dir 5):
    D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/A1.jpg Moved to D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B3.jpg.temp_unique_suffix(0B)
    D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B3.jpg Moved to D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/A1.jpg(0B)
    D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B3.jpg.temp_unique_suffix Moved to D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B3.jpg(0B)
replacing A2.jpg(idx in dir 1) with B2.jpg(idx in dir 4):
    D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/A2.jpg Moved to D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B2.jpg.temp_unique_suffix(0B)
    D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B2.jpg Moved to D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/A2.jpg(0B)
    D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B2.jpg.temp_unique_suffix Moved to D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B2.jpg(0B)
replacing A3.jpg(idx in dir 2) with B1.jpg(idx in dir 3):
    D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/A3.jpg Moved to D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B1.jpg.temp_unique_suffix(0B)
    D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B1.jpg Moved to D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/A3.jpg(0B)
    D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B1.jpg.temp_unique_suffix Moved to D:/workspace/2021wizzi_utils/temp/StackOverFlow/scanner_files/B1.jpg(0B)
  • Related