Working with os and shutil Modules in Python


What Are os and shutil in Python?

os module: Offers functions for interacting with the operating system, such as navigating directories, creating/removing folders, environment variables, etc.

shutil module: Extends os by providing higher-level operations like copying, moving, and deleting files and directories.



Basic Directory Operations with os

Get Current Working Directory

import os
print(os.getcwd())

Output:

/home/user/myproject

List Files and Folders

files = os.listdir()
print(files)

Output:

['file1.txt', 'images', 'data.csv']

Create a Directory

os.mkdir('new_folder')

Or create nested folders:

os.makedirs('parent_folder/child_folder')

Remove a Directory

os.rmdir('new_folder')  # only removes empty folders

To remove non-empty folders:

os.removedirs('parent_folder/child_folder')  # nested folders

Rename a File or Folder

os.rename('old_name.txt', 'new_name.txt')


Working with Files & Directories using shutil


Copy a File

import shutil
shutil.copy('file1.txt', 'copy_file1.txt')

This copies the content and metadata.


Copy a Directory

shutil.copytree('source_folder', 'destination_folder')

Move a File or Directory

shutil.move('file1.txt', 'backup/file1.txt')

Delete a File

os.remove('file_to_delete.txt')

Delete a Directory

shutil.rmtree('folder_to_delete')

Use this with caution. It deletes the entire directory tree!


Check File or Directory Exists

print(os.path.exists('file1.txt'))         # True/False
print(os.path.isdir('myfolder'))           # True/False
print(os.path.isfile('file1.txt'))         # True/False


Practical Use Case: Backup Script

import os, shutil

src = 'project_data'
dst = 'backup/project_data'

if os.path.exists(src):
    shutil.copytree(src, dst)
    print("Backup successful!")
else:
    print("Source folder not found.")

Best Practices

  • Use os.path.join() to build OS-independent paths.
  • Always check os.path.exists() before copying/deleting.
  • Wrap dangerous operations in try-except to avoid crashes.