How to copy, move, rename, and delete files/folders using Python
Python’s shutil
and os
modules are used for these tasks.
Copying Files/Folders:
- Use
shutil.copy(src, dst)
for copying files. - Use
shutil.copytree(src, dst)
for copying entire folders.
Example:
import shutil
shutil.copy('source.txt', 'destination.txt') # Copies file
shutil.copytree('source_folder', 'backup_folder') # Copies entire folder
Moving/Renaming:
- Use
shutil.move(src, dst)
to move or rename files/folders.
shutil.move('old_name.txt', 'new_name.txt') # Renames
shutil.move('file.txt', 'backup/file.txt') # Moves file
Deleting:
- Use
os.remove(path)
to delete files. - Use
shutil.rmtree(path)
to delete folders (recursively).
import os
os.remove('file.txt')
shutil.rmtree('folder_name')
These tools allow Python scripts to manage files like a basic file explorer.