Introduction
Copying files in Python can be done easily using the shutil
module, which provides a high-level interface for file operations. The shutil.copy()
and shutil.copy2()
functions are commonly used to copy files. These functions can copy files from one location to another while preserving metadata.
Using shutil.copy()
The shutil.copy()
function copies the content of the source file to the destination file. It does not copy the metadata such as file permissions, creation, and modification times.
Syntax
import shutil
shutil.copy('source_file.txt', 'destination_file.txt')
Example
Let’s say you have a file named example.txt
and you want to copy it to copy_of_example.txt
.
import shutil
try:
shutil.copy('example.txt', 'copy_of_example.txt')
print("File copied successfully.")
except FileNotFoundError:
print("The source file does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Output
File copied successfully.
Using shutil.copy2()
The shutil.copy2()
function copies the content and metadata of the source file to the destination file. This includes file permissions, creation, and modification times.
Syntax
import shutil
shutil.copy2('source_file.txt', 'destination_file.txt')
Example
import shutil
try:
shutil.copy2('example.txt', 'copy_of_example.txt')
print("File copied successfully with metadata.")
except FileNotFoundError:
print("The source file does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Output
File copied successfully with metadata.
Handling Exceptions
It’s important to handle exceptions that may occur during the copying process, such as file not found errors or permission errors.
Example
import shutil
try:
shutil.copy('example.txt', 'copy_of_example.txt')
print("File copied successfully.")
except FileNotFoundError:
print("The source file does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Output
The source file does not exist.
Copying Files in a Directory
You can copy multiple files in a directory by iterating over the files and using the shutil.copy()
function.
Example
Let’s copy all .txt
files from source_directory
to destination_directory
.
import shutil
import os
source_directory = 'source_directory'
destination_directory = 'destination_directory'
try:
os.makedirs(destination_directory, exist_ok=True)
for file_name in os.listdir(source_directory):
if file_name.endswith('.txt'):
source_file = os.path.join(source_directory, file_name)
destination_file = os.path.join(destination_directory, file_name)
shutil.copy(source_file, destination_file)
print("Files copied successfully.")
except FileNotFoundError:
print("The source directory does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Output
Files copied successfully.
Using pathlib for Copying Files
The pathlib
module in Python 3.4+ provides an object-oriented approach for handling filesystem paths. You can use it in combination with shutil
to copy files.
Example
from pathlib import Path
import shutil
source_file = Path('example.txt')
destination_file = Path('copy_of_example.txt')
try:
shutil.copy(source_file, destination_file)
print("File copied successfully.")
except FileNotFoundError:
print("The source file does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Output
File copied successfully.
Conclusion
Copying files in Python is a straightforward and efficient process using the shutil
module. By using shutil.copy()
and shutil.copy2()
, you can copy files with or without metadata. Additionally, handling exceptions ensures that your program responds appropriately to errors during the copying process. Understanding how to copy files is essential for file management tasks in Python applications.