Python Program to Copy a File


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

In computing, a file is a collection of data or information that is stored in a computer system under a specific name and location. It could be any type of data such as text, image, audio, video, program executable or any other format that can be stored on a computer.


Python Code :

The below Python program copies a file:


# Import the shutil module
import shutil

# Define the source and destination paths
src_file = 'path/to/source/file'
dst_file = 'path/to/destination/file'

# Copy the file using shutil.copy()
shutil.copy(src_file, dst_file)

# Print a message to indicate that the file has been copied
print(f"{src_file} has been copied to {dst_file}.")

In this program, we first import the shutil module, which provides functions for copying files and directories.

We then define the source and destination paths as strings. Replace ‘path/to/source/file’ and ‘path/to/destination/file’ with the actual paths to the source and destination files on your system.

We use the shutil.copy() function to copy the file from the source path to the destination path. The shutil.copy() function preserves the file’s metadata, such as permissions, timestamps, and file mode.

Finally, we print a message to indicate that the file has been copied successfully. Replace ‘{src_file}’ and ‘{dst_file}’ with the actual paths to the source and destination files in your message.

Note that if the destination file already exists, shutil.copy() will overwrite it without prompting. If you want to avoid overwriting files, you can use shutil.copy2() instead, which preserves the file’s metadata and also raises a FileExistsError if the destination file already exists.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co