shutil for File Operations
Copy, move, and archive files.
What Is shutil?
The shutil (shell utilities) module offers high-level file operations: copying, moving, deleting trees, and creating archives. It builds on os for everyday tasks.
import shutil, os
os.makedirs('/tmp/shutil_demo', exist_ok=True)
with open('/tmp/shutil_demo/a.txt', 'w') as f:
f.write('hello')
print('created a.txt')Copying a File
shutil.copy(src, dst) copies a file's contents and permission bits to a new location.
import shutil, os
os.makedirs('/tmp/shutil_demo', exist_ok=True)
with open('/tmp/shutil_demo/src.txt', 'w') as f:
f.write('data')
shutil.copy('/tmp/shutil_demo/src.txt', '/tmp/shutil_demo/copy.txt')
print(os.path.exists('/tmp/shutil_demo/copy.txt'))All lessons in this course
- Running Commands with subprocess
- Capturing Output
- Environment and os Module
- shutil for File Operations