Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python - Directories (Complete Guide for Beginners)

 In Python, directories (also called folders) are used to organize files in a structured way. Instead of keeping all files in one place, you can create, rename, list, and remove directories using Python.

Python provides the built-in os module to work with directories easily.

In this tutorial, you will learn how to manage directories in Python with clear examples.


What is a Directory?

A directory is a folder that contains files and other folders.

Example structure:

Project/
 ├── file1.txt
 ├── file2.txt
 └── images/

Importing OS Module

To work with directories, we use the os module.

import os

1. Get Current Working Directory

The working directory is the folder where Python is currently running.

Example:

import os

print(os.getcwd())

Output:

C:\Users\YourName\Project

2. Change Directory

You can change the current working directory using chdir().

Example:

import os

os.chdir("C:/Users/YourName/Documents")

print(os.getcwd())

3. Create a New Directory

Use os.mkdir() to create a single folder.

Example:

import os

os.mkdir("MyFolder")

print("Folder created")

4. Create Multiple Nested Directories

Use os.makedirs() to create folders inside folders.

Example:

import os

os.makedirs("ParentFolder/ChildFolder")

print("Nested folders created")

5. List Files and Directories

Use os.listdir() to view all items in a directory.

Example:

import os

items = os.listdir()

print(items)

Output:

['file1.txt', 'file2.txt', 'MyFolder']

6. Remove a Directory

Use os.rmdir() to delete an empty folder.

Example:

import os

os.rmdir("MyFolder")

print("Folder deleted")

7. Remove Nested Directories

Use os.removedirs() to delete multiple empty folders.

Example:

import os

os.removedirs("ParentFolder/ChildFolder")

print("Nested folders deleted")

8. Check if Directory Exists

Example:

import os

if os.path.exists("MyFolder"):
    print("Folder exists")
else:
    print("Folder not found")

9. Rename a Directory

Use os.rename() to rename folders.

Example:

import os

os.rename("OldFolder", "NewFolder")

print("Folder renamed")

Real-World Example: Project Folder Setup

import os

base_folder = "MyProject"

if not os.path.exists(base_folder):
    os.mkdir(base_folder)

os.makedirs(f"{base_folder}/images")
os.makedirs(f"{base_folder}/docs")

print("Project structure created")

Real-World Example: File Organizer

import os

folders = ["Images", "Videos", "Docs"]

for folder in folders:
    if not os.path.exists(folder):
        os.mkdir(folder)
        print(folder, "created")

Directory Methods Summary

MethodDescription
os.getcwd()Get current directory
os.chdir()Change directory
os.mkdir()Create folder
os.makedirs()Create nested folders
os.listdir()List contents
os.rmdir()Remove empty folder
os.removedirs()Remove nested folders
os.rename()Rename folder

Common Mistakes

Mistake 1: Folder already exists

❌ Wrong:

os.mkdir("MyFolder")

✔ Causes FileExistsError


Mistake 2: Removing non-empty folder

os.rmdir("MyFolder")

✔ Only works for empty folders


Mistake 3: Wrong path usage

os.chdir("wrong/path")

✔ Causes FileNotFoundError


Safe Directory Handling Example

import os

folder = "TestFolder"

if not os.path.exists(folder):
    os.mkdir(folder)
    print("Created safely")

Conclusion

Directories in Python help you organize files efficiently and build structured applications.

You learned:

  • How to create and delete folders
  • How to list and navigate directories
  • How to rename and manage folder structures
  • Real-world automation examples

Mastering directory handling is essential for file systems, automation tools, and large-scale applications.




Post a Comment

0 Comments