How to copy a file in Python
How to copy a file in Python.
Here's a step-by-step tutorial on how to copy a file in Python:
Step 1: Import the required modules
To copy a file in Python, you need to import the shutil
module. This module provides a high-level interface for file operations.
import shutil
Step 2: Specify the source file and destination
Next, specify the path of the source file that you want to copy and the destination where you want to copy it. Make sure to include the complete file path.
source_file = 'path/to/source_file.txt'
destination = 'path/to/destination_folder'
Step 3: Use shutil.copy()
to copy the file
Now, use the shutil.copy()
function to copy the file. This function takes two arguments: the source file and the destination folder.
shutil.copy(source_file, destination)
Step 4: Handling exceptions
It's important to handle any exceptions that may occur during the file copying process. The most common exception to handle is shutil.Error
, which is raised when source and destination are the same file or if there are any permission issues.
try:
shutil.copy(source_file, destination)
except shutil.Error as e:
print(f"Error: {e}")
except Exception as e:
print(f"Error: {e}")
Step 5: Verify the file copy
To verify that the file has been successfully copied, you can check if the destination file exists using the os.path.exists()
function from the os
module.
import os
destination_file = os.path.join(destination, os.path.basename(source_file))
if os.path.exists(destination_file):
print("File copied successfully!")
else:
print("File copy failed!")
Step 6: Full code example
Here's the complete code example for copying a file in Python:
import shutil
import os
source_file = 'path/to/source_file.txt'
destination = 'path/to/destination_folder'
try:
shutil.copy(source_file, destination)
except shutil.Error as e:
print(f"Error: {e}")
except Exception as e:
print(f"Error: {e}")
destination_file = os.path.join(destination, os.path.basename(source_file))
if os.path.exists(destination_file):
print("File copied successfully!")
else:
print("File copy failed!")
That's it! You have successfully copied a file in Python using the shutil
module.