Rename multiple files in a directory in Python

ghz 3months ago ⋅ 96 views

I'm trying to rename some files in a directory using Python.

Say I have a file called CHEESE_CHEESE_TYPE.*** and want to remove CHEESE_ so my resulting filename would be CHEESE_TYPE

I'm trying to use the os.path.split but it's not working properly. I have also considered using string manipulations, but have not been successful with that either.

Answers

You can use the os module to rename files in a directory by leveraging string manipulation. Here's a step-by-step guide on how to achieve this:

Example Code

import os

# Specify the directory containing the files
directory = '/path/to/your/directory'

# Iterate over all files in the directory
for filename in os.listdir(directory):
    # Check if the file name starts with 'CHEESE_'
    if filename.startswith('CHEESE_'):
        # Remove 'CHEESE_' from the filename
        new_filename = filename.replace('CHEESE_', '', 1)  # Replace only the first occurrence

        # Create full path for old and new file names
        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: {old_file} to {new_file}')

Explanation

  1. Directory Path: Set the directory variable to the path where your files are located.
  2. Iterate Over Files: Use os.listdir(directory) to get a list of files in the directory.
  3. Check File Name: Use startswith('CHEESE_') to find files that start with the specified prefix.
  4. Rename: Use replace('CHEESE_', '', 1) to remove the prefix from the filename. The 1 ensures that only the first occurrence is replaced.
  5. Full Paths: Use os.path.join(directory, filename) to get the full path for both the old and new filenames.
  6. Rename File: Use os.rename(old_file, new_file) to rename the file.

Important Notes

  • Make sure to adjust the directory variable to point to your specific directory.
  • Be careful when renaming files, especially in production environments, as this will change the actual file names.