python

Python – How to copy files from one directory to another

In this tutorial, we are going to see how to copy files from one directory to another using shutil.copy().
 

What is Shutil?

The “shutil” module helps you automate the copying of files and directories. This allows you to open, read, write and close files. It is a utility module that can be used to accomplish tasks such as: copying, moving, or deleting files.
 

 

How to copy files from one directory to another

In the following code, we are going to copy the “file.txt” to “/home/user/doc/” directory and return the path of the newly created file.

import shutil

filePath = shutil.copy('file.txt', '/home/user/doc/')
print(filePath)

Output:

/home/user/doc/file.txt

Some important points:

  • If the destination directory already contains a file with the same name, it will be overwritten.
  • If the destination path is not valid, it will generate an error.
 

How to copy files from one directory to another with a new name

The code below, will copy the file file1.txt to another location with the name file2.txt.

import shutil
filePath = shutil.copy('file1.txt', '/home/user/doc/file2.txt')

Some important points:

  • If the destination file already exists, it will be overwritten.
  • If the destination path is not valid, it will generate an error.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *