Some text some message..
Back Python os module 27 Jul, 2025

The Python os module is one of the most essential modules for interacting with the Operating System — especially for tasks like:

  • file creation,

  • file reading/writing,

  • directory operations,

  • environment variables,

  • path handling, etc.


🔧 1. Creating Files Using os

The os module doesn't directly create or write files (you use open() for that), but you can use it to check existence and create empty files:

✅ Create an Empty File:

import os

file_path = "example.txt"

# Create an empty file if it doesn't exist
if not os.path.exists(file_path):
    with open(file_path, 'w') as f:
        pass  # or f.write('') to write an empty string

✍️ 2. Writing and Reading Files (with open())

os sets the path, but actual read/write is done with open().

🔹 Writing to a File:

with open("example.txt", "w") as f:
    f.write("Hello, world!\n")
    f.write("This is a second line.\n")

🔹 Appending to a File:

with open("example.txt", "a") as f:
    f.write("Appended line.\n")

🔹 Reading from a File:

with open("example.txt", "r") as f:
    content = f.read()
    print(content)

📁 3. Directory (Folder) Operations

✅ Create a Single Folder:

os.mkdir("my_folder")

✅ Create Nested Folders:

os.makedirs("parent_folder/child_folder/grandchild", exist_ok=True)

✅ Check If Folder Exists:

if os.path.exists("my_folder"):
    print("Folder exists")

❌ 4. Deleting Files and Folders

🔹 Delete a File:

os.remove("example.txt")

🔹 Delete an Empty Folder:

os.rmdir("my_folder")

🔹 Delete a Folder with Contents:

Use shutil:

import shutil
shutil.rmtree("parent_folder")

🔄 5. Renaming / Moving Files or Folders

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

📂 6. List Files or Directories

files = os.listdir(".")  # List everything in current directory
print(files)

# List only files
only_files = [f for f in os.listdir('.') if os.path.isfile(f)]

📌 7. Path Handling (Recommended to use os.path or pathlib)

file_path = os.path.join("folder", "file.txt")
print(file_path)

# Get absolute path
abs_path = os.path.abspath(file_path)
print(abs_path)

# Get directory name
print(os.path.dirname(abs_path))

# Get file name
print(os.path.basename(abs_path))

# Check file extension
print(os.path.splitext(file_path))

🌐 8. Environment Variables

# Read env variable
db_path = os.getenv("DB_PATH", "default_path.db")

# Set env variable (session-based, does not persist)
os.environ["MY_ENV"] = "value"
print(os.environ["MY_ENV"])

⚠️ Tips & Best Practices

Task Preferred
Cross-platform paths Use os.path.join() or pathlib.Path()
Directory creation Use os.makedirs(..., exist_ok=True)
Path manipulations Use os.path or pathlib
Deleting folders with content Use shutil.rmtree()

🧠 Summary: When to Use What?

Operation Module
Path building, checking, existence os, os.path
File read/write open()
File/Folder creation/removal os, shutil
Environment variables os.environ, os.getenv()