DEV Community

Avnish
Avnish

Posted on

Python Copy File – Copying Files to Another Directory

To copy files in Python, you can use the shutil module, which provides a copyfile() function to copy the contents of a file from one location to another. Here are 5 examples of copying files to another directory:

Example 1:

import shutil

source_file = 'source_directory/file.txt'
destination_dir = 'destination_directory/'

shutil.copyfile(source_file, destination_dir + 'file.txt')
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • source_file: Path to the file you want to copy.
  • destination_dir: Path to the directory where you want to copy the file.
  • shutil.copyfile(source_file, destination_dir + 'file.txt'): This line copies the contents of source_file to the specified destination directory with the name 'file.txt'.

Example 2:

import shutil

source_file = 'source_directory/file.txt'
destination_file = 'destination_directory/destination_file.txt'

shutil.copyfile(source_file, destination_file)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Similar to the first example, but here we specify a different name for the destination file (destination_file.txt).

Example 3:

import shutil

source_dir = 'source_directory/'
destination_dir = 'destination_directory/'

shutil.copytree(source_dir, destination_dir)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • shutil.copytree() copies an entire directory tree (including all files and subdirectories) from the source directory to the destination directory.

Example 4:

import shutil

source_dir = 'source_directory/'
destination_dir = 'destination_directory/'

shutil.copytree(source_dir, destination_dir, dirs_exist_ok=True)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • In Python 3.8 and later, you can use the dirs_exist_ok parameter to allow the destination directory to exist. If it doesn't exist, it will be created.

Example 5:

import shutil

source_dir = 'source_directory/'
destination_dir = 'destination_directory/'

shutil.copy2(source_dir + 'file.txt', destination_dir + 'file.txt')
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • shutil.copy2() copies the file's contents and also preserves its metadata (timestamps, permissions, etc.).

These examples illustrate various ways to copy files and directories in Python using the shutil module. Make sure to replace 'source_directory', 'destination_directory', and 'file.txt' with your actual file paths and names.

Top comments (0)