0

I am trying to rename those images so image_0596(2) changed to iamge_0596 After that I want to increment the file number so previous image_0596 => image_0597 and previous image_0598 => image_0599 ...... However, the block of my code doesn't replace anything.

from itertools import count
import os
def main():
path =''
lst = os.listdir(path)
os.chdir(path)
for filename in os.listdir(path):
    if filename.endswith('.jpg'):
        filename = ("image_%04i.jpg" % i for i in count(1))

enter image description here

2
  • The main function needs to be indented Commented Apr 13, 2022 at 19:19
  • Why should changing the value of filename cause any change to the actual name of the file on the disk? Did you try to research about how to rename files, for example by using a search engine? Commented Apr 13, 2022 at 19:21

1 Answer 1

2

Well, itertools.count is totally the wrong tool here. And, of course, you are not calling os.rename at all.

This is not a trivial problem. You cannot rename image_0597 until image_0598 is out of the way. You'll need to do them in reverse order. I think this will do what you want. You might replace the os.rename calls with print calls before you do this for real.

import os
def main():
    files = [i for i in os.listdir('.') if i[-4:] == '.jpg']
    files.sort(reverse=True)
    for f in files:
        if f.startswith('image_0596'):
            break
        i = f.find('_')
        j = f.find('.')
        nbr = int(f[i+1:j])
        newname = 'image_%04d.jpg' % (nbr+1)
        os.rename( f, newname )
    os.rename( 'image_0596.jpg', 'image_0597.jpg' )
    os.rename( 'image_0596(2).jpg', 'image_0596.jpg' )

main()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for reply. Yet, I understand the idea but I still facing error said "system can not find the file specified image_1157 -> image_1158". Yes image_1157 is the last file in the folder
Did you mean image_1157.jpg? Or have you changed the code to eliminate the extensions?
Also note that this code ASSUMES the files are all in the current directory. If you are passing a pathname to os.listdir, then that path will need to be prepended to the file names.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.