Organizing a large number of digital files can be a daunting task, especially when they have long and complicated names. To streamline this process, we developed a simple Python script to remove suffixes from digital file names. This small tool can save a lot of time and help you keep your files organized. Check out how it works and give it a try!
Why Use This Script?
If you frequently deal with batches of images that have unnecessary suffixes in their filenames, this script will help you quickly rename them, making your file management much easier.
Step-by-Step Guide
Step 1:Â Create a folder and save a code file in it named renameFiles.py.
Step 2:Â Inside this folder, create another folder named images.
Step 3: Place the images you want to rename inside the images folder.
Step 4:Â Open your command line and navigate to the folder containing renameFiles.py.
Step 5:Â Run the following command:
python3 renameFiles.py
Step 6:Â Done! Your images will now have the suffixes removed from their filenames.
The Code
Here’s the Python code for renameFiles.py:
import os
def rename_files_in_directory(directory):
# Get a list of all files in the directory
files = os.listdir(directory)
for filename in files:
# Skip directories
if os.path.isdir(os.path.join(directory, filename)):
continue
# Split the filename at the first underscore and keep only the part before it
new_filename = filename.split('_')[0] + os.path.splitext(filename)[1]
# Get the full path to the old and new file
old_file = os.path.join(directory, filename)
new_file = os.path.join(directory, new_filename)
# Rename the file
os.rename(old_file, new_file)
print(f'Renamed: {filename} to {new_filename}')
# Replace 'images' with the name of the folder with your images
directory_path = 'images'
rename_files_in_directory(directory_path)
How It Works
The script works by iterating through all files in the specified directory. For each file, it removes the suffix by splitting the filename at the underscore and keeping the first part, then adds the original file extension back. Finally, it renames the file and prints out a confirmation.
Conclusion
We hope this little script helps you manage your image files more efficiently. Feel free to reach out with any questions or feedback!
Happy coding! 💻
Comments