Can anyone HELP me for my problem .. Im a newbie in python ! I want to create a script to rename files in a dir. that dir has 400 files .png .. startswith 001.png , 002.png to 400.png ! I want to rename them startswith 000.png to 399.png .. Please Help!!

Dani AI

Generated

This thread’s goal (shift 001..400.png → 000..399.png) is best handled by parsing the numeric prefix, computing new = old − 1, and doing the renames in a collision-safe way. The two reliable options are: (A) a one-pass rename in strictly increasing numeric order (works when 000 is not present), or (B) a two-pass rename that moves matched files to unique temporary names first, then to final names — this always avoids clobbering. The snippet below shows a compact, portable two-pass approach; it only touches files whose names start with three digits and “.png”.

import os, re

pat = re.compile(r'^(\d{3})\.png$')
items = []
for n in os.listdir('.'):
    m = pat.match(n)
    if m:
        items.append((int(m.group(1)), n))

items.sort()                     # sort by numeric prefix
mapping = []
for num, src in items:
    new = num - 1
    if new < 0:
        continue                 # skip negatives (or handle as needed)
    dst = str(new).zfill(3) + '.png'
    mapping.append((src, dst))

# quick collision check
if len(set(d for s, d in mapping)) != len(mapping):
    raise SystemExit('Target-name collision detected; aborting.')

# two-pass: src -> unique tmp -> final
tmp_names = []
i = 0
for src, dst in mapping:
    tmp = '__tmp__%04d' % i
    os.rename(src, tmp)
    tmp_names.append((tmp, dst))
    i += 1

for tmp, dst in tmp_names:
    os.rename(tmp, dst)

Notes: run this on a copy (or print the mapping first) to verify results. This builds on ’s and ’s suggestions to restrict to .png and to validate prefixes, and it avoids the enumerate/version issues flagged on very old PyS60 builds (if you are on an old PyS60, either upgrade or use simple index counters instead of enumerate).

Read the documentation of os module to find suitable command and use a loop and string formatting to do zero padded number:

print('%03i.txt' % 5)

Output:

005.txt

If you're using linux, this may be handled more simply with a bash script.

It`s simpel with python to,and this is a python forum.
save script in folder with files and run.

import os, glob

for numb,name in enumerate(glob.glob('*png')):
    os.rename(name, '{num:03d}.png'.format(num=numb))
commented: easy +10

Meister snippsat's solution is easy, but be careful, it will rename any .png file in the directory. You might want to make sure that the name starts with an integer at least.

im only using pys60 .. Symbian ! Python says no module named glob :(

Try.

import os

for numb,name in enumerate(os.listdir(".")):
    if name.endswith(".png"):
        os.rename(name, '{num:03d}.png'.format(num=numb))

Or.
http://people.csail.mit.edu/kapu/symbian/python_old.html

glob, fnmatch
Standard Python modules that are not part of PyS60 distribution, with slight modifications
so they work with PyS60.
Glob allows directory listing with wild cards, fnmatch is used by glob. Used by sync, btconsole.

I think pyS60 use python 2.5.4,then you have to use old string formatting like this.
You should of course mention in first post that you use pyS60.

import os

for numb,name in enumerate(os.listdir(".")):
    if name.endswith(".png"):
        os.rename(name, '%03i.png' % numb)

thankyou so much for all of you .. im noob in python ! i want to learn more in python .. sorry for my bad english :)

i try to run the code above .. python say's
for numb,name in enumerate(os.listdir("e:Py")):
NameError: name 'enumerate' is not defined

Implement it yourself

from __future__ import generators # does your python need this ?

def enumerate(iterable, start=0):
    i = start - 1
    for item in iterable:
        i += 1
        yield (i, item)

You should uppgarde your pyS60 version if enumerate() not work.
enumerate() was new in python 2.3 in 2003.
It`s difficult to write/learn python if you cannot use features implemented last 10 years.

the most widely used pys60 is v1.45 and is a port of python 2.2.2. the pys60 v1.9.7 that is a python 2.5 port that is less used.
for pys60 there are many modules for manipulating files and dirs, as an example I can suggest the pow_light fm module or fman module.there is also a shutil module for pys60.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.