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
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
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
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
Sources
- https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
- https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
- https://www.pythonforbeginners.com/os/pythons-os-module
- https://www.tutorialspoint.com/python/os_path_methods.htm
- https://www.tutorialspoint.com/python/string_replace.htm
- https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python