![]() |
In Python, copying and replacing files is a common task facilitated by modules like `shutil` and `os`. This process involves copying a source file to a destination location while potentially replacing any existing file with the same name. Leveraging functions like `shutil.copy2` and `os.remove`, this operation is crucial for updating or maintaining file versions. In this article, we will see how to copy and replace files in Python. Copy And Replace Files In PythonBelow are some of the ways by which we can copy and replace files in Python:
Python Copy And Replace Files Using
|
import shutil import os def copy_and_replace(source_path, destination_path): if os.path.exists(destination_path): os.remove(destination_path) shutil.copy2(source_path, destination_path) # Source and destination file paths source_file = 'path/to/source_file.txt' destination_file = 'path/to/destination_file.txt' # Copy and replace copy_and_replace(source_file, destination_file) |
Output:
shutil.move()
In this example, the `copy_and_replace` function takes a source file path and a destination directory. It extracts the filename from the source path, constructs the destination path within the specified directory, removes any existing file with the same name, then moves the source file to the destination, effectively copying and replacing it. The example usage copies the 'main.py' file to the 'dummy' directory, providing a print confirmation upon successful completion.
import shutil import os def copy_and_replace(source_file, destination_directory): filename = os.path.basename(source_file) destination_path = os.path.join(destination_directory, filename) if os.path.exists(destination_path): os.remove(destination_path) shutil.move(source_file, destination_path) print (f "File '{filename}' copied and replaced successfully." ) # Example usage: source_file_path = 'main.py' destination_directory = 'dummy' copy_and_replace(source_file_path, destination_directory) |
Output:
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |