user506710
user506710

Reputation:

Renaming multiple files in python

I wanted to know what is the easiest way to rename multiple files using re module in python if at all it is possible.

In my directory their are 25 files all with the file names in the format ' A unique name followed by 20 same characters.mkv '

What I wanted was to delete all the 20 characters.

How can I do this using Python if at all it is possible :)

Upvotes: 5

Views: 9671

Answers (5)

moinudin
moinudin

Reputation: 138477

To get the new name:

>>> re.sub(r'.{20}(.mkv)', r'\1', 'unique12345678901234567890.mkv')
'unique.mkv'

Or without regex:

>>> 'unique12345678901234567890.mkv'[:-24] + '.mkv'
'unique.mkv'

To rename the file use os.rename(old, new): http://docs.python.org/library/os.html#os.rename

To get a list of the files to rename use glob.glob('*.mkv'): http://docs.python.org/library/glob.html#glob.glob

Putting that all together we get:

for filename in glob.glob('*.mkv'):
    if len(filename) > 24:
        os.rename(filename, filename[:-24] + '.mkv'

Upvotes: 6

MattH
MattH

Reputation: 38265

Something like:

>>> import os
>>> doIt = False
>>> for filename in ( x for x in os.listdir('.') if x.endswith('.mvk')):
...     newname = filename[:-24] + filename[-4:]
...     if doIt:
...         os.rename(filename,newname)
...         print "Renaming {0} to {1}".format(filename,newname)
...     else:
...         print "Would rename {0} to {1}".format(filename,newname)
...

When manipulating files, always have a dryrun. Change doIt to True, to actually move the files.

Upvotes: 0

user225312
user225312

Reputation: 131807

You need to use glob and os.rename. The rest if for you to figure it out!

And yes, this is entirely possible and easy to do in Python.

Upvotes: -1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799300

Use glob to find the filenames, slice the strings, and use os.rename() to rename them.

Upvotes: 0

Karl Knechtel
Karl Knechtel

Reputation: 61643

Since you are cutting out a specific number of characters from an easily identified point in the string, the re module is somewhat overkill. You can prepare the new filename as:

new_name = old_name.rsplit('.', 1)[0][:-20] + '.mkv'

To find the files, look up os.listdir (or, if you want to look into directories recursively, os.walk), and to rename them, see os.rename.

The re module would be useful if there are other .mkv's in the directory that you don't want to rename, so that you need to do more careful checking to identify the "target" filenames.

Upvotes: 0

Related Questions