3

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.

3 Answers 3

3

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

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

Comments

2

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.