shutil in python
shutil in python
June 1, 2024
- module for high-level operations for copying, removing, moving files/directories.
Copy
import shutil
# copies file located at source. If file already exists, it's overwritten
shutil.copy("main.py", "main2.py")
# copy2 is similar to copy except preserves metadata
shutil.copy2("main.py", "main2.py")
# copytree - copies full directory
shutil.copytree(".folder1", "myfolder")
Move
import shutil
shutil.move(".folder1/file.txt", "file.txt") # moves file
Delete
import shutil
shutil.rmtree("folder1") # deletes folder