I found myself having to edit the filenames of several video files. Each video filename had the same leading and ending text that I wanted to remove. This seemed like a good candidate for my first DIY Python script.

For this project I will be

  • Getting a list of files from a given directory
  • Removing text from the beginning of a string
  • Removing text from the end of a string
  • Updating the filename of a file

Getting a List of Files From a Directory

Copy to Clipboard

The first thing we need to do is import some functions from the os module

  • listdir – Returns a list of entries in the given directory
  • path.isfile – Returns True if path is an existing regular file.
  • path.join – Joins one or more path components intelligently

With those os commands in place, we just need build the return list using list comprehension. This will only add items to the list that are files.

Removing Text From a String

Copy to Clipboard

For my needs, I don’t need anything more sophisticated than a string replace where I replace the beginning and end text that I want to remove with an empty string.

Renaming a File

Copy to Clipboard

We use the os method “rename” to rename the file. Note, you will need to include the full path if you are editing files that are not in the current working directory which is why we are calling join on the new and old filenames.

Putting It All Together

Copy to Clipboard