Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

A Python Script to Increment File Names Starting at a Specific Number

blog/cards/a-python-script-to-increment-file-names-starting-at-a-specific-number.jpg

This could be useful when adding a new file in between a list of files that were already ordered by number.

Quick Jump: Demo Video

A few days ago I had a use case come up where I had 175 images sitting on disk and each file started with the pattern of 001-, 002- and so on.

I manually numbered them while writing descriptive file names but since I’m a human being I made an error and accidentally duplicated 67- twice so I ended up with an incorrectly ordered set of file names.

What I wanted to do was take the 2nd copy of 67- and change that to 68- and then bump up the rest of the file names by +1 and since I didn’t want to do that manually, here we are.

The video below goes over using the script and walks through most of the source code too.

Demo Video

Timestamps

  • 0:08 – Use cases for why I created the script
  • 3:15 – Using the inc-file-names script
  • 5:23 – Going over all of the source code of (argparse driven Python CLI)
  • 8:16 – Getting the base name of a file path with Python
  • 9:30 – Controlling how many times you split a string by a delimiter
  • 11:18 – Figuring out if and how much to increment the file name’s prefix by
  • 14:22 – Composing the new file name and either printing or renaming it
  • 16:02 – Ways to maybe improve this script if you want to have some fun

What do you plan to use this script for? Let me know below.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per month (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments