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

harry Im
  • 19
  • 4
  • The `main` function needs to be indented – Liam Apr 13 '22 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](https://meta.stackoverflow.com/questions/261592) about how to rename files, for example by [using a search engine](https://duckduckgo.com/?q=python+rename+file)? – Karl Knechtel Apr 13 '22 at 19:21

1 Answers1

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()
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 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 – harry Im Apr 13 '22 at 19:40
  • Did you mean `image_1157.jpg`? Or have you changed the code to eliminate the extensions? – Tim Roberts Apr 13 '22 at 19:44
  • 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. – Tim Roberts Apr 13 '22 at 19:45