How to Copy a File or Folder in Python 


               


How to Copy a File or Folder in Python



Python


In this article, we show how to copy a file or folder in Python.

In Python, it is relatively simple to copy a file or a folder.

We'll first go over how to copy a file. Then, we'll go over how to copy a folder.


How to Copy a File

The code to copy a file in Python is shown below.



So, first, we must import the shutil and os modules.

So, the code above copies the file, file.txt, in the same existing folder and names it file2.txt.

If the file you are copying is in the current working directory, then you do not need to specify the full path to the file.

In this example, we copy the file, file.txt, in the folder, C:\\Users\\David, and place the copy in the same folder. However, you can place the copied file in any folder. You would just specify the folder as the second parameter.

If you copy the file in a different folder other than the current folder where the original file is located, you don't have to specify the name of the file.

The following code below illustrates this.



This code, above, will copy the file.txt file and save it to this new folder (Projects) with the same filename, file.txt.

However, you can also specify the filename if you want.

Note that if you are copying a file in a folder and placing the copied file in the same folder, the two files cannot have the same name. If they do, this will throw a SameFileError.


How to Copy a Folder

So, now , we go over how to copy a folder in Python.

Unlike copying a file which is done with the copy() function, copying a folder uses the copytree() function.

This is shown below.



So, using the shutil.copytree() function, we can copy a folder.

In this example, we copy the PythonProjects folder and name the copied folder, PythonProjects_backup.

So, this is how we can copy a file or a folder in Python.


Related Resources



HTML Comment Box is loading comments...