-2

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
Binary111
  • 149
  • 4
  • 15
  • 3
    Googling "python list files in directory" and "python rename file" should be a good starting point... shouldn't be too hard to find – Felix May 02 '17 at 19:32
  • 1
    _"The best I got was 601.jpg, 601.jpg, and it was the same for every file."_ Interesting. Please post the code that did this. Although it didn't work, it will make a useful starting-off point. – Kevin May 02 '17 at 19:33
  • @Kevin I just added the code I had! – Binary111 May 02 '17 at 19:41
  • Possible duplicate of same code and question [here](http://stackoverflow.com/questions/37467561/renaming-multiple-files-in-a-directory-using-python). – NineTail May 02 '17 at 20:24

1 Answers1

2

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
tdelaney
  • 73,364
  • 6
  • 83
  • 116