Header Ads Widget

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

Python OS File/Directory Methods (Complete Guide for Beginners)

 The os module in Python provides powerful functions to interact with the operating system, allowing you to work with files and directories easily.

With os module methods, you can:

  • Create and remove files and folders
  • Navigate directories
  • Check file/folder existence
  • Rename files and directories
  • List contents of folders

In this tutorial, you will learn important Python OS file and directory methods with clear examples.


Importing OS Module

Before using OS methods, you must import it.

import os

1. os.name

Returns the name of the operating system.

Example:

import os

print(os.name)

Output:

posix (Linux/Mac)
nt (Windows)

2. os.getcwd()

Returns the current working directory.

Example:

import os

print(os.getcwd())

3. os.chdir()

Changes the current working directory.

Example:

import os

os.chdir("C:/Users")

print(os.getcwd())

4. os.listdir()

Lists all files and directories in a folder.

Example:

import os

print(os.listdir())

5. os.mkdir()

Creates a single directory.

Example:

import os

os.mkdir("MyFolder")

print("Folder created")

6. os.makedirs()

Creates nested directories.

Example:

import os

os.makedirs("ParentFolder/ChildFolder")

print("Nested folders created")

7. os.rmdir()

Removes an empty directory.

Example:

import os

os.rmdir("MyFolder")

print("Folder removed")

8. os.removedirs()

Removes nested empty directories.

Example:

import os

os.removedirs("ParentFolder/ChildFolder")

print("Nested folders removed")

9. os.remove()

Deletes a file.

Example:

import os

os.remove("file.txt")

print("File deleted")

10. os.rename()

Renames files or directories.

Example:

import os

os.rename("old.txt", "new.txt")

print("Renamed successfully")

11. os.path.exists()

Checks if file or directory exists.

Example:

import os

if os.path.exists("file.txt"):
    print("File exists")
else:
    print("File not found")

12. os.path.isfile()

Checks if path is a file.

Example:

import os

print(os.path.isfile("file.txt"))

13. os.path.isdir()

Checks if path is a directory.

Example:

import os

print(os.path.isdir("MyFolder"))

14. os.path.join()

Joins path components safely.

Example:

import os

path = os.path.join("Folder", "file.txt")

print(path)

Real-World Example: Project Setup Automation

import os

project = "MyProject"

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

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

print("Project structure created")

Real-World Example: File Cleaner Tool

import os

files = ["temp1.txt", "temp2.txt"]

for file in files:
    if os.path.exists(file):
        os.remove(file)
        print(file, "deleted")

OS Methods Summary

MethodDescription
os.nameOS type
os.getcwd()Current directory
os.chdir()Change directory
os.listdir()List files/folders
os.mkdir()Create folder
os.makedirs()Create nested folders
os.rmdir()Remove empty folder
os.removedirs()Remove nested folders
os.remove()Delete file
os.rename()Rename file/folder
os.path.exists()Check existence
os.path.isfile()Check file
os.path.isdir()Check folder
os.path.join()Join paths

Common Mistakes

Mistake 1: Removing non-empty folder

❌ Wrong:

os.rmdir("Folder")

✔ Only works if folder is empty


Mistake 2: Wrong file path

os.remove("wrong.txt")

✔ Causes FileNotFoundError


Mistake 3: Overwriting system paths

✔ Always double-check paths before operations


Safe OS Handling Example

import os

file = "data.txt"

if os.path.exists(file):
    os.remove(file)
    print("Deleted safely")

Conclusion

Python OS module provides powerful tools for managing files and directories.

You learned:

  • File and directory operations
  • Path checking and navigation
  • Safe file handling techniques
  • Real-world automation examples

Mastering OS methods helps you build system tools, automation scripts, and file management applications.




Post a Comment

0 Comments