How to copy, move, rename, delete files/folders in Python

python-copy-move-rename-delete-files-folders-feature-image

In this tutorial, we’re gonna look at way to copy, move, rename, and delete files/folders in Python using shutil module.

Related Posts:
How to read/write files in Python

Copy file/folder in Python

Copy file

We use shutil.copy(source, destination) to copy the file at source to destination folder.

*Notes:
– This function returns path of the copied file.
– If destination is a filename, it will be used as the new name of the copied file.

Copy folder

We use shutil.copytree(source, destination) to copy entire folder (including all folders and files inside) at source to destination folder.

*Notes:
– This function returns path of the copied folder.
– If destination folder already exists, the function will throw a FileExistsError error.

Move file/folder in Python

We use shutil.move(source, destination) to move file or folder (including all folders and files inside) at source to destination folder.

*Notes:
– This function returns path of new location.
– If destination is a filename or a folder that doesn’t exist, it will be used as the new name of the moved file/folder.
– If there is already a file/folder with the same filename in destination, it will throw an error.
Important: If we move a file to a folder that doesn’t exist, the file WILL be moved and renamed WITHOUT file extension.

Rename file/folder in Python

We can use shutil.move(source, destination) with the source same as destination to rename the file or folder.

Delete file/folder in Python

Permanent delete

We have 3 functions for specific cases:
os.unlink(path): delete file at path.
os.rmdir(path): delete folder (must be empty) at path.
shutil.rmtree(path): delete folder (including all files and folder inside) at path.

Safe delete

Instead of permanently deleting files/folders, we can use third-party send2trash module that will files or folders to trash or recycle bin.

At first, we need to install send2trash module, open cmd, then run:
pip install send2trash

Once the installation is successful, we can see send2trash folder at Python\Python[version]\Lib\site-packages.
Now we’re gonna import the module and use its send2trash() function:



By grokonez | January 13, 2019.


Related Posts


Got Something To Say:

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

*