Home > Mobile >  Why does my program to rename .jpg files not number them correctly when there are files with other e
Why does my program to rename .jpg files not number them correctly when there are files with other e

Time:01-30

enter image description here

def main():
   path = r'blahblah'
   lst = os.listdir(path)
   len = 0
   for i in lst:
       if i.endswith(".jpg"):
           len =1
   len_file = int(math.log(len,10)) 1
   z_fill_num = len_file
   count=1
   os.chdir(path)
   for count, filename in enumerate(os.listdir(path)):
    if filename.endswith('.jpg'):
        os.rename(filename, 'image_' str(count 1).zfill(z_fill_num) '.jpg')
        count =1
    elif not filename.endswith('.jpg'):
        pass

I was modifying script to replace all the filename to image_001, image_002,... but when there is another extension file beside '.jpg', the script renames the first image file to image_002 instead of image_001. How do I specify to the script that I want to rename only jpg files?

CodePudding user response:

You have to change your loop as you enumerate over the list of files and therefore reset the counter on each loop iteration. Change the following line:

for count, filename in enumerate(os.listdir(path)):

to this:

for filename in os.listdir(path):

Also, you have to initialize the counter with zero in order to name the first file image_0000.

CodePudding user response:

I believe your problem is due to the fact you initialize count=1 and then use str(count 1) in your renaming function, which means the first rename would use 2.

I think you need to change your rename line to:

os.rename(filename, 'image_' str(count).zfill(z_fill_num) '.jpg')

Edit: I just saw that you override your count variable with the count in the for-loop. You shouldn't do that in any scenario. Consider renaming it or not using it at all.

CodePudding user response:

Suppose I have these files:

ls -1
file-a.jpg
file-b.jpg
file-c.jpg
file-d.jpg
file-e.jpg

With Python, with pathlib, you could rename them with increasing numbers like so:

from pathlib import Path 
w=4
p=Path(base_path)

for i, fn in enumerate(
                sorted(
                    [f for f in p.glob('*.jpg') if f.is_file()],  # sort as appropriate
                        key=lambda x: x.stem), 1):
    new_name=fn.with_name(f"{fn.stem}-{i:0{w}d}{fn.suffix}")
    print(f'Renaming "{fn}" to "{new_name}"')
    fn.rename(new_name)

Prints:

Renaming "/tmp/test/file-a.jpg" to "/tmp/test/file-a-0001.jpg"
Renaming "/tmp/test/file-b.jpg" to "/tmp/test/file-b-0002.jpg"
Renaming "/tmp/test/file-c.jpg" to "/tmp/test/file-c-0003.jpg"
Renaming "/tmp/test/file-d.jpg" to "/tmp/test/file-d-0004.jpg"
Renaming "/tmp/test/file-e.jpg" to "/tmp/test/file-e-0005.jpg"

And results in:

ls -1
file-a-0001.jpg
file-b-0002.jpg
file-c-0003.jpg
file-d-0004.jpg
file-e-0005.jpg
  •  Tags:  
  • Related