Search code examples
pythonpython-2.7batch-rename

Renaming files with python to 1.jpg, 2.jpg, etc


First I would like to say I want to do this in python 2.7!

Hi, I have a folder full of images named 1.jpg, 2.jpg, 3.jpg, etc. All the way up to 600.jpg.

I would like to rename them 600 higher, so 601.jpg, 602.jpg, 603.jpg, etc. All the way up to 1200.jpg.

I am honestly not quite sure where to start, so any help would be useful. It doesn't seam like it should be hard but I was not able to name them in ascending order. The best I got was 601.jpg, 601.jpg, and it was the same for every file.

This is what I have currently, it's been altered a few times, and now all I get is an error.

import os
path = '/Users/antse/OneDrive/Documents/Instagram/set_2'
files = os.listdir(path)
i = 601

for file in files:
    os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.jpg'))
    i = i+1

Solution

  • One of the problems with your approach is that listdir doesn't come back in order from 1.jpg ..., and it includes any other files or subdirectories. But there is no need to list the directory - you already know the pattern of what you want to change and its a hassle to deal with other files that may be there.

    import os
    
    path = '/Users/antse/OneDrive/Documents/Instagram/set_2'
    for i in range(1, 601):
        old_name = os.path.join(path, '{}.jpg'.format(i))
        new_name = os.path.join(path, '{}.jpg'.format(i+600))
        try:
            os.rename(old_name, new_name)
        except OSError as e:
            print 'could not rename', old_name, e