Example Python script for renaming files with an auto increment number at the end of the filename. Very easy to follow script and guide to help you.
I created this script because every now and then I have to rename a lot of files.
Like images, to a one named-based with increment number files. This script is very easy to rename files, it keeps the right file-extension and add’s a auto incremented number at the end.
Renaming files in python is easy. But renaming and keeping unique names is a bit more difficult.
With this rename and auto increment name changer it’s very ease to do all your renaming jobs.
let’s say you want to convert this list with images to something you understand.
DSC_0000.JPG
SBCS0000.JPG
DSCN0001.jpg
IMG_0001.jpg
DCP_0001.jpg
DSCF0001.jpg
PICT0000.JPG
MVC-0000.JPG
using the name “holiday-spain”
The names will come out like this:
holiday-spain-0001.jpg
holiday-spain-0002.jpg
holiday-spain-0003.jpg
holiday-spain-0004.jpg
holiday-spain-0005.jpg
holiday-spain-0006.jpg
holiday-spain-0007.jpg
Just change
the start folder (mine is : “profile_photos”) name the newName for the new name of the files and the startIncNumber to with what number it should start.
startfolder = os.path.join(dir_path, "profile_photos")
newName = "your-great-new-file-name"
startIncNumber = 1
Have fun! ```python ''' author: Theo van der Sluijs url: itheo.tech copyright: CC BY-NC 4.0 creation date: 22-12-2018
This script takes a folder and renames all the files to the same name with auto increment numbers.
It keeps the extensions of each file unchanged
Great for renaming images!
No extra pip install needed. ''' import os
class RenameFiles: def init(self, folder=None, new_name=None, start_nr=0): self.startFolder = folder self.newName = new_name self.startNr = start_nr
def loop_files(self, start_folder=None, new_name=None, start_nr=0):
if start_folder is None and self.startFolder is not None:
start_folder = self.startFolder
if new_name is None and self.newName is not None:
new_name = self.newName
if self.startNr >= start_nr:
start_nr = self.startNr
for filename in os.listdir(start_folder):
file = os.path.join(startfolder, filename)
filename, file_extension = os.path.splitext(file)
number = '{0:04}'.format(start_nr)
new_filename = "{}-{}{}".format(new_name, number, file_extension.lower())
newfile = os.path.join(startfolder, new_filename)
os.rename(file, newfile)
print("Done :{}".format(filename))
start_nr += 1
if name == 'main': dir_path = os.path.dirname(os.path.realpath(file)) startfolder = os.path.join(dir_path, "profile_photos") newName = "your-great-new-file-name" startIncNumber = 1
r = RenameFiles()
r.loop_files(startfolder, newName, startIncNumber)