Home  >  Article  >  Backend Development  >  How to Rename Multiple Files in a Directory Using Python

How to Rename Multiple Files in a Directory Using Python

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 04:41:30958browse

How to Rename Multiple Files in a Directory Using Python

Renaming Multiple Files in a Directory Using Python

Renaming multiple files in a directory can be a tedious task if done manually. Python, however, provides several options for automating this process, making it more efficient and accurate.

Approach:

Using os.path.split

import os
folder = 'dir'
files = os.listdir(folder)

for file in files:
    # Split the filename and extension
    filename, ext = os.path.splitext(file)

    # Modify the filename
    modified_filename = filename.split('_')[1]

    # Combine the modified filename with the extension
    new_file = modified_filename + ext

    # Rename the file
    os.rename(os.path.join(folder, file), os.path.join(folder, new_file))

Using String Manipulation:

import os
folder = 'dir'
files = os.listdir(folder)

for file in files:
    if file.startswith('CHEESE_'):
        # Remove 'CHEESE_' from the filename
        new_file = file[7:]

        # Rename the file
        os.rename(os.path.join(folder, file), os.path.join(folder, new_file))

Using os.rename

import os
folder = 'dir'
files = os.listdir(folder)

for file in files:
    if file.startswith('CHEESE_'):
        # Get the new filename
        new_file = file[7:]

        # Use os.rename() to change the filename
        os.rename(os.path.join(folder, file), os.path.join(folder, new_file))

All of these approaches accomplish the desired outcome of renaming files in a directory, removing the "CHEESE_" prefix and retaining the original extension.

The above is the detailed content of How to Rename Multiple Files in a Directory Using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn