Horje
Copy Files and Rename in Python

Copying and renaming files is a common task in programming, and Python provides several ways to accomplish this efficiently. In this article, we will explore some commonly used methods for copying files and renaming them: using the shutil module’s copy() and pathlib module’s Path class. Each method has its advantages, and choosing the right one depends on the specific requirements of your project.

How To Copy Files And Rename Them In Python?

Below, are the generally used method for How To Copy Files And Rename Them In Python.

Copy Files And Rename using shutil.copy()

The shutil module in Python is a powerful utility for file operations, including copying files. The copy() function from this module allows us to copy a file from one location to another. Here’s a simple example: This example uses the shutil.copy() method to copy the file and shutil.move() to rename the copied file in the destination folder.

Python
import shutil

def copy_and_rename(src_path, dest_path, new_name):
    # Copy the file
    shutil.copy(src_path, dest_path)

    # Rename the copied file
    new_path = f"{dest_path}/{new_name}"
    shutil.move(f"{dest_path}/{src_path}", new_path)

# Example usage
source_file = "example.txt"
destination_folder = "destination_folder"
new_file_name = "renamed_example.txt"

copy_and_rename(source_file, destination_folder, new_file_name)
print("Successfully Created File and Rename")

Output

Successfully Created File and Rename

Copy Files And Rename Using pathlib.Path

The pathlib module was introduced in Python 3.4 to provide an object-oriented interface for file system paths. The Path class includes the rename() method, making it convenient for both copying and renaming files: In this example, the Path class is used to create path objects, and rename() is employed to both copy and rename the file in the destination folder.

Python
from pathlib import Path

def copy_and_rename_pathlib(src_path, dest_path, new_name):
    # Create Path objects
    src_path = Path(src_path)
    dest_path = Path(dest_path)

    # Copy and rename the file
    new_path = dest_path / new_name
    src_path.rename(new_path)

# Example usage
source_file = "example.txt"
destination_folder = "destination_folder"
new_file_name = "renamed_example.txt"

copy_and_rename_pathlib(source_file, destination_folder, new_file_name)
print("Successfully Created File and Rename")

Output :

Successfully Created File and Rename



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Convert Python File to PDF Convert Python File to PDF
How To Fix Recursionerror In Python How To Fix Recursionerror In Python
How to mask a systemd unit in Linux? How to mask a systemd unit in Linux?
10 Best Linux Tablets for 2024 10 Best Linux Tablets for 2024
How to Manage Packages in Red Hat-based Linux? How to Manage Packages in Red Hat-based Linux?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13