0

I have 400 files in a directory (with .png extensions). They start with the name 005.png and go up to 395.png.

I want to rename them using os.rename:

os.rename(006.png,005.png) 

In other words, I want to shift all the numbers down one, renaming the file 005.png to 004.png and renaming 395.png to 394.png, and so on.

I don't want to do this manually, because it would take too long:

os.rename(005.png,004.png) os.rename(006.png,005.png) ... 

How can I do this simply? I am using the s60 2nd edition FP3.

Thanks in advance!

1
  • 4
    "Please give me a code" — we don't do that here. Show us what you've tried and where you've run into problems, and we will try to help. We won't write your code for you. Commented Aug 19, 2012 at 13:57

3 Answers 3

3

You can use a simple loop:

for i in xrange(4, 396): os.rename(str(i).zfill(3) + ".png", str(i-1).zfill(3) + ".png")) 

and that's about it :)

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

Comments

2

A loop is the easiest indeed. As an alternative to str(i).zfill(3) + ".png", you could use

template = "{0:03d}.png" for i in range(4, 396): os.rename(template.format(i), template.format(i-1)) 

Comments

1
import os path = r"C:\your_dir"#i've added r for skipping slash , case you are in windows os.chdir(path)#well here were the problem , before edit you were in different directory and you want edit file which is in another directory , so you have to change your directory to the same path you wanted to change some of it's file files = os.listdir(path) for file in files: name,ext = file.split('.') edited_name=str(int(name)-1) os.rename(file,edited_name+'.'+ext) 

hopefully that's what are you looking up for

4 Comments

I try your code and python say's "os.rename(file,newName) TypeError: coercing to Unicode: need string or buffer, int found >>>"
Sir .. it says >>> ===== RESTART ===== >>> Traceback (most recent call last): File "ped.py", line 1061, in run_click File "D:\Ped.temp\Unnamed1.py", line 7, in ? os.rename("file","newName") OSError: [Errno 2] No such file or directory >>> why ? I put the exact file path on it !
i've make the final edit , and i'm sure 100% it's going to work :)
Sir .. Thankyou for your reply ! Your code works .. But my 3 digit file name becames 2 .. File: 005.png became 05.png .. i want it to be: 005.png become 004.png and so on .. 005.png to 004.png 006.png to 005.png and so on .. up to 395.png became 394.png ! Thankyou very much ..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.