pythonrenamesequential

How can I sequentially rename files in a folder using Python, without renaming files in a messy way?


Hi I hope someone can help me, i'm trying to rename some .png inside a folder, 0.png 1.png 2.png ... 3000.png

the problem is that it processes files in a messy way, for example 10.png renames it to 3.png Instead it should be 11.png etc.

I would like it to rename like this instead: 0.png rename to -> 1.png 1.png rename to -> 2.png ... 10.png rename to -> 11.png

Some advice? Thank you

I tried with this:

import os

path = r'/Desktop//Name'
newpath = r'/Desktop/Name2'

count = 1
for f in os.scandir(path):
    if str(f.name).endswith('.png'):
        new_file = '' + str(count)+'.png'
        src = os.path.join(path, f.name)
        dst = os.path.join(newpath, new_file)
        os.rename(src, dst)
        count += 1
 
os.scandir(path).close()

Solution

  • I'm writing this without testing, but how about this? It should do what you need. It appears that maybe there are files other than *.png files in the directory. If not, then you can simplify this a bit more...

    import os
    import shutil
        
        path = r'/Desktop//Name'
        newpath = r'/Desktop/Name2'
        
        for f in os.scandir(path):
            if str(f.name).endswith('.png'):
                file_number = int(str(f.name).split('.')[0])
                new_file_number = file_number + 1
                new_file = '%s.png' % new_file_number
                src = os.path.join(path, f.name)
                dst = os.path.join(newpath, new_file)
                shutil.move(src, dst)
         
        os.scandir(path).close()