Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch Renaming of Files in a Directory

Is there an easy way to rename a group of files already contained in a directory, using Python?

Example: I have a directory full of *.doc files and I want to rename them in a consistent way.

X.doc -> "new(X).doc"

Y.doc -> "new(Y).doc"

like image 916
Nate Avatar asked Oct 22 '08 13:10

Nate


People also ask

How do I batch rename multiple files at once?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.


1 Answers

I prefer writing small one liners for each replace I have to do instead of making a more generic and complex code. E.g.:

This replaces all underscores with hyphens in any non-hidden file in the current directory

import os [os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')] 
like image 121
Cesar Canassa Avatar answered Sep 21 '22 06:09

Cesar Canassa