rename files sorted by size

August 27, 2010 at 04:59:16
Specs: Windows 7
hello all,

I've had some luck with simple scripts, but this one is out of my league.

I'm trying to write a script that goes into a subfolder called "Images" ( 2 levels down), sorts all files according to size and renames them with a fixed sting and an increasing counter.

/ <-script is run in root folder

-Folder 1 <-one level down
--Images <-fixed name for this subfolder (2 levels down from root)
---file.jpg,filex,jpg,filey,jpg <-files in folder above, original file names are random

-Folder 2
--Images
---file.jpg,filex,jpg,filey,jpg

I would like the files in the "Image" sub folders to be sorted according to size and renamed "img001.jpg , img002.jpg, img003.jpg" etc. The counter needs to start from 0 for each Images folder. The files always have the jpg extention.

I would appreciate a working script :-) but if its too much trouble I'd be more than happy with a skeleton code that I can try to fill on my own..

Thanks in advance!


See More: rename files sorted by size

Report •


#1
August 27, 2010 at 19:13:07
if you can download Python

import os
import fileinput
root=os.path.join("C:\\","test")
for r,d,f in os.walk(root):
   if r.endswith("Images"):
      store={}
      tfiles=len(f)
      counter=1      
      for file in f:
         filename=os.path.join(r,file)
         size=os.path.getsize(filename)
         store[filename]=size
      for k in sorted(store.keys()):         
         fpath,fname=os.path.split(k)[0],os.path.split(k)[-1]
         splitfname=fname.split(".")
         newfile = ".".join(splitfname[:-1])+str(counter).zfill(tfiles)+"."+str(splitfname[-1])
         newfile = os.path.join(fpath,newfile)
         counter+=1
         try:
            os.rename(k,newfile)
         except Exception,e:
            print e

GNU win32 packages | Gawk


Report •

#2
August 27, 2010 at 19:20:28
ghostdog's in a Python kind of mood >=) 2-in-a-row!

Report •

#3
August 27, 2010 at 19:52:06
Try this batch script, not fully tested. You will have to change paths etc to suit your setup. No allowance has been made for filenames containing spaces.

@echo off
cls
setlocal enabledelayedexpansion

pushd Path\to\folder1\.jpg\files\||echo Pushd failed - job terminated&&exit /b
call :process

pushd Path\to\folder2\.jpg\files\||echo Pushd failed - job terminated&&exit /b
call :process

exit /b


:process
set nbr=001

for /f "tokens=*" %%1 in ('dir /b /os *.jpg') do (
    rem ren %%1 img!nbr!.jpg
    echo OldFilename=%%1
    echo NewFilename=img!nbr!.jpg
    echo.
    pause>nul

    set /a nbr+=1
    if !nbr! lss 10 set nbr=00!nbr!
    if !nbr! gtr 9  if !nbr lss 100 set nbr=0!nbr!
)
popd



Report •

Related Solutions

#4
August 28, 2010 at 05:30:20
ghostdog and matt123, thank you for the reply!

I decided to use the dos script because I don't know anything about python. Some little tweaks and it works perfect :)


Report •


Ask Question