Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename many files sequentially Python

Tags:

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.

like image 750
Licia Avatar asked Sep 13 '26 07:09

Licia


1 Answers

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

like image 91
Mauro Baraldi Avatar answered Sep 15 '26 21:09

Mauro Baraldi