Licia
Licia

Reputation: 65

Rename many files sequentially Python

My training on Python is ongoing and I'm currently trying to rename sequentially many files that have this kind of root and extension:

Ite_1_0001.eps

Ite_2_0001.eps

Ite_3_0001.eps

Ite_4_0001.eps

However, I'm trying to rename all these files as follows:

Ite_0001.eps

Ite_0002.eps

Ite_0003.eps

Ite_0004.eps

So I'm proceeding in this way:

for path, subdirs, files in os.walk(newpath):
   num = len(os.listdir(newpath))
   for filename in files:
       basename, extension = os.path.splitext(filename)
       for x in range(1, num+1):
           new_filename = '_%04d' % x + extension
       os.rename(os.path.join(newpath, filename), os.path.join(newpath, new_filename))

It's not working at all because all the files are erased from the directory and when running the script once at a time I have this:

First run: _00004

Second run: _00005

.... and so on.

Could any one have some tips that could help me to achieve this task :).

Thank you very much for your help.

Upvotes: 3

Views: 685

Answers (3)

Mauro Baraldi
Mauro Baraldi

Reputation: 6560

You could test the approach with a list of strings. So you do not run the risk of deleting the files. ;-)

files = ["Ite_1_0001.eps", "Ite_2_0001.eps", "Ite_3_0001.eps", "Ite_4_0001.eps",]

for f in files:
    # Get the value between underscores. This is the index.
    index = int(f[4:f.index('_', 4)])
    new_name = '_%04d' % index
    # Join the prefix, index and sufix file
    print ''.join([f[:3], new_name, f[-4:]])

Ite_0001.eps

Ite_0002.eps

Ite_0003.eps

Ite_0004.eps

Upvotes: 3

Mikedev
Mikedev

Reputation: 326

I write a function that if you give in input your basename it returns the correct name.

def newname(old_name):
    num = old_name[4]
    return (old_name[0:3] + old_name[5:-1] + num)

Upvotes: 0

Shaig Khaligli
Shaig Khaligli

Reputation: 5485

You can dynamically change the thing you're substituting in within your loop, like so

import os, re
n = 1
for i in os.listdir('.'):
    os.rename(i, re.sub(r'\(\d{4}\)', '(Ite_) ({n})'.format(n=n), i))
    n += 1

Upvotes: 2

Related Questions