πŸ“‚ Python File Handling
Estimated reading: 3 minutes 28 views

πŸ—‚οΈ Python OS File/Directory Methods – Create, Rename, Delete & Navigate

🧲 Introduction – Why Use the os Module?

Python’s built-in os module lets you interact with the operating system, allowing you to work with files, folders, and directories programmatically. Whether you need to create, rename, move, delete, or navigate directories, os provides platform-independent functions to automate these tasks.

🎯 In this guide, you’ll learn:

  • Core os module methods for file/directory handling
  • How to list, rename, delete, and navigate folders
  • Best practices for checking and manipulating paths

πŸ“¦ Importing the os Module

import os

βœ… This module provides all file/directory-related functions.


πŸ“ Directory Management Methods

βœ… os.getcwd() – Get Current Working Directory

print(os.getcwd())

βœ… Returns the absolute path of the current working directory.


βœ… os.chdir(path) – Change Directory

os.chdir("/path/to/folder")

βœ… Changes the current working directory to the specified path.


βœ… os.listdir(path='.') – List Files/Folders

print(os.listdir())

βœ… Lists all files and directories in the given path (default: current directory).


βœ… os.mkdir("folder") – Create New Directory

os.mkdir("new_folder")

βœ… Creates a new directory (fails if it already exists).


βœ… os.makedirs("path/to/nested/folder")

os.makedirs("folder1/folder2/folder3")

βœ… Recursively creates nested directories.


βœ… os.rmdir("folder") – Remove Empty Directory

os.rmdir("new_folder")

βœ… Deletes an empty folder. Use shutil.rmtree() for non-empty folders.


πŸ“„ File Handling with OS Methods

βœ… os.remove("file.txt") – Delete File

os.remove("data.txt")

βœ… Permanently deletes the specified file.


βœ… os.rename("old.txt", "new.txt")

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

βœ… Renames or moves a file.


βœ… os.path.exists(path) – Check if File/Dir Exists

if os.path.exists("myfile.txt"):
    print("Exists!")

βœ… Safely checks whether the file or folder exists before performing operations.


βœ… os.path.isdir(path) / os.path.isfile(path)

os.path.isdir("my_folder")
os.path.isfile("file.txt")

βœ… Distinguishes between files and directories.


βœ… os.path.join() – Join Path Components

path = os.path.join("folder", "file.txt")
print(path)  # Output: folder/file.txt (platform-independent)

βœ… Safely concatenates paths using the correct separator (/ or \ depending on OS).


🧹 Cleanup & Recursive Operations

For non-empty folder deletion, use:

import shutil
shutil.rmtree("folder_name")

βœ… Recursively deletes a folder and all its contents.


πŸ’‘ Best Practices

  • βœ… Always check file/folder existence with os.path.exists() before removing or renaming.
  • βœ… Use os.path.join() to maintain cross-platform compatibility.
  • βœ… Use with open() for file access alongside os for management.
  • ⚠️ Don’t use os.rmdir() on non-empty foldersβ€”use shutil.rmtree().

πŸ“Œ Summary – Recap & Next Steps

The os module is a powerful tool for automating filesystem tasks like directory navigation, file manipulation, and structural organization. It simplifies batch file processing, backup scripts, and file-based automation across platforms.

πŸ” Key Takeaways:

  • βœ… Use os.getcwd(), os.chdir(), and os.listdir() for directory navigation
  • βœ… Use os.mkdir(), os.makedirs(), os.remove(), os.rename() for filesystem changes
  • βœ… Check existence and join paths safely with os.path functions

βš™οΈ Real-World Relevance:
Used in deployment scripts, log file rotation, automated backups, and data preprocessing pipelines.


❓ FAQ Section – Python OS File/Directory Methods

❓ How do I check if a file exists before deleting it?

βœ… Use:

if os.path.exists("file.txt"):
    os.remove("file.txt")

❓ What’s the difference between os.mkdir() and os.makedirs()?

βœ… mkdir() creates one folder. makedirs() creates nested directories recursively.

❓ How do I delete a folder that contains files?

βœ… Use:

import shutil
shutil.rmtree("folder_name")

❓ Can I join folder and file names safely?

βœ… Use os.path.join("folder", "file.txt") – works on all operating systems.

❓ What’s the difference between os.path.isdir() and isfile()?

βœ… isdir() checks for a folder. isfile() checks for a regular file.


Share Now :

Leave a Reply

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

Share

Python OS File/Directory Methods

Or Copy Link

CONTENTS
Scroll to Top