Python automating file renaming in bulk

python @ Freshers.in

Automating repetitive tasks not only saves time but also minimizes the chance of human error. Python, known for its simplicity and versatility, is a powerful tool for such automation tasks. This guide will show you how to use Python for automating a common task: renaming a batch of files in a directory.

Understanding the task

File renaming can be tedious, especially when dealing with a large number of files. Automating this process can be a real time-saver. Python’s built-in libraries make it easy to script these kinds of tasks.

Make sure Python is installed on your system. No external libraries are required for this task, as we’ll be using Python’s standard libraries.

Writing the Python script

Defining the renaming function:

Create a function to rename files. This example will add a prefix to each file in the directory:

import os
def rename_files(directory, prefix):
    for filename in os.listdir(directory):
        if not filename.startswith(prefix):
            new_name = prefix + filename
            os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))

Executing the script:

Call the function with the target directory and desired prefix:

directory_path = '/freshers/sample/directory'
file_prefix = 'new_'
rename_files(directory_path, file_prefix)

To test this script, create a directory with a few sample files. You can name them file1.txt, file2.txt, etc. Run the script and observe that the files are renamed with the specified prefix, e.g., new_file1.txt, new_file2.txt.

Refer more on python here :

Author: user