Write a Python program to copy files and folders using the shutil module
To handle file and folder operations like copying, Python provides the shutil module. Below is a simple program demonstrating both:
1. Copying a File
import shutil
# Copy a single file
shutil.copy('source_file.txt', 'destination_file.txt')
This copies the contents of source_file.txt into destination_file.txt.
2. Copying a Folder
import shutil
# Copy an entire folder with all files and subfolders
shutil.copytree('source_folder', 'destination_folder')
This duplicates the whole source_folder into destination_folder.
Note: The destination folder must not already exist, or
copytree()will raise an error.
Complete Program Example:
import shutil
# Copy file
shutil.copy('notes.txt', 'backup/notes_backup.txt')
# Copy directory
shutil.copytree('project_data', 'project_data_backup')
Make sure the destination folder (backup or project_data_backup) doesn’t exist before running the program.
