-1

I have a folder with lots of subfolders. Each of subfolders has different type of image files. I'm trying to rename those files by specific format. Data looks like this:

folder
        \ sub1\file0.jpg
        \ sub1\file1.jpg
        \ sub1\file2.png
        .
        .
        .
        \ sub2\xxx.png
        \ sub2\yyy.jpg
        \ sub2\zzz.png
        .
        .
        .

Desired output:

folder
        \ sub1\file-01.jpg
        \ sub1\file-02.jpg
        \ sub1\file-03.png
        .
        .
        .
        \ sub2\file-01.png
        \ sub2\file-02.jpg
        \ sub2\file-03.png
        .
        .
        .

By far, I have tried following code but it doesn't work out.

import os

dir_name = "D:/folder"     
for root, dirs, files in os.walk(dir_name, topdown=False):
    for file in files:
        file_name = os.path.splitext(file)[0]#file name no ext
        extension = os.path.splitext(file)[1]
        dir_name = os.path.basename(root)
        os.rename(root+"/"+file, root+"/"+"file"+"s%"+extension)
Ahmed Salah
  • 851
  • 2
  • 10
  • 29
ah bon
  • 9,293
  • 12
  • 65
  • 148
  • 1
    "It doesn't work [out]" may be an accurate description of what happens, but we need a bit more. Did you try to see what each step does by insterting `print` commands between each step with the intermediate results? – Jongware Nov 30 '18 at 09:52
  • `os.rename(root+"/"+file, root+"/"+"file"+"s%"+extension)` `s%` are you sure you're not missing your index and the proper formatting? – Jean-François Fabre Nov 30 '18 at 09:59
  • 1
    you could have an increment counter for each type of extension, and reinitialize them for every new sub folder – Surya Tej Nov 30 '18 at 10:00

2 Answers2

2

This is one approach using enumerate.

Demo:

import os

dir_name = "D:/folder"      
for root, dirs, files in os.walk(dir_name, topdown=False):
    for num, file in enumerate(files, 1):   #enumerate to get number
        src =  os.path.join(root, file)
        file_s = os.path.splitext(file)
        dest = os.path.join(root, "{0}-{1}.{2}".format(file_s[0], str(num).rjust(2, "0"), file_s[1]))   #Form destination file name
        os.rename(src, dest)   #Rename. 
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

os.rename(root+"/"+file, root+"/"+"file"+"s%"+extension)

You're using the %s string formatting syntax wrong (I'm assuming that's what you intend to do). Read more about it here. Just as a reminder, you need an actual variable to be inserted in place of %s. I'm sure you can figure out how to implement that. (the other answer gives a possible solution, too)

In fact, I'd suggest using string formatting for root, file, and extension as well - and while you're at that, consider using f-strings instead of the %s syntax.

selplacei
  • 124
  • 1
  • 10