Python OS Module

Introduction

The os module in Python provides functions to interact with the operating system. It allows you to work with files, folders, system paths, and environment variables and execute system commands.


Task you want to doos Module Feature
Get current directoryos.getcwd()
Change directoryos.chdir()
Create/Remove foldersos.mkdir() / os.rmdir()
List files and foldersos.listdir()
Work with environment variablesos.environ
Join file paths safelyos.path.join()
Delete a fileos.remove()
Run system commandsos.system()

Importing OS Module


Directory Operations

Get the current working directory


Create and Delete Directories

Create a new folder

Remove a folder (only if empty)

Create multiple nested directories

Remove nested directories


File Handling

Delete a file

Rename a file


Path Operations (os.path)

FunctionDescription
os.path.join()Safely join folder and file names
os.path.exists()Check if path/file exists
os.path.isdir()Check if the path is file
os.path.isfile()Check if the path is a file
os.path.getsize()Get file size in bytes

Example


Environment Variables

View environment variables

Fetch a specific variable


Run System Commands

Open Command Prompt / Terminal command


Examples of Python OS Module






os doesn’t have copy directly, so use system command



Check File Permissions




Python List MCQs

Python List MCQ Quiz (Random 10 Questions)

Python String MCQs

Python String Quiz (Random 10 of 50)

🔄 Refresh the page to get a new set of questions.

⏳ Time Left: 120 seconds

Python Read/Write CSV

What is a CSV File?

CSV stands for Comma-Separated Values and is commonly used for tabular data like spreadsheets.

Python has a built-in csv module for handling CSV files.


Write to CSV File

Write Rows Manually


Write Multiple Rows (Loop / List)


Read CSV File

Read and Print Entire File


Read CSV as Dictionary

💡 Best when the first row contains headers.


Write CSV Using Dictionary


Append to a CSV File


Handling Custom Delimiters

Example: Semi-colon ; separated file


Real Example: CSV Filtering

Print only rows where Age > 25


Summary

TaskMethod
Write rowwriter.writerow()
Write multiple rowswriter.writerows()
Read CSVcsv.reader()
Read as dictcsv.DictReader()
Write dictcsv.DictWriter()
Append data"a" mode
Change delimiterdelimiter=";"

Python Read/Write JSON

JSON in Python

JSON (JavaScript Object Notation) is used for storing and exchanging data, commonly in APIs and configuration files.

Python has a built-in module:

import json

Write (Save) JSON to a File

Example Dictionary/Data

data = {
    "name": "Deepesh",
    "age": 30,
    "skills": ["Python", "Selenium", "Automation"]
}

Save to JSON file

import json

with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

indent=4 makes the JSON formatted & readable.


Read (Load) JSON from a File

import json

with open("data.json", "r") as file:
    content = json.load(file)
    print(content)

Output

{'name': 'Deepesh', 'age': 30, 'skills': ['Python', 'Selenium', 'Automation']}

Now content is a Python dictionary, and you can access elements like:

print(content["name"])
print(content["skills"][1])

Convert Python Data ↔ JSON String

Convert Python → JSON string

import json

person = {"city": "Delhi", "pin": 110001}
json_string = json.dumps(person)
print(json_string)

Convert JSON string → Python


Update JSON File

import json

# Read existing content
with open("data.json", "r") as file:
    data = json.load(file)

# Modify data
data["age"] = 31
data["skills"].append("API Testing")

# Write back to file
with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

Work with Lists in JSON

Example JSON file (employees.json)

[
    {"id": 1, "name": "Ankit"},
    {"id": 2, "name": "Riya"}
]

Add a new record

import json

with open("employees.json", "r") as file:
    employees = json.load(file)

employees.append({"id": 3, "name": "Aman"})

with open("employees.json", "w") as file:
    json.dump(employees, file, indent=4)

Summary

TaskFunction
Write Python → JSON filejson.dump()
Read JSON file → Pythonjson.load()
Python → JSON stringjson.dumps()
JSON string → Pythonjson.loads()

Python Read/Write Excel File

openpyxl for Excel Handling

Install openpyxl (if not installed)

pip install openpyxl

from openpyxl import Workbook

wb = Workbook()                # Create workbook
ws = wb.active                 # Select active sheet
ws.title = "Students"          # Rename sheet

# Write data
ws['A1'] = "Name"
ws['B1'] = "Marks"
ws['A2'] = "Deepesh"
ws['B2'] = 85

wb.save("students.xlsx")       # Save file
print("File created successfully")

Using append()

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

data = [
    ["Name", "Marks"],
    ["Ankit", 90],
    ["Riya", 88],
    ["Aman", 76]
]

for row in data:
    ws.append(row)

wb.save("marks.xlsx")
print("Data written successfully")

Read the whole sheet of data

from openpyxl import load_workbook

wb = load_workbook("marks.xlsx")
ws = wb.active

for row in ws.rows:
    for cell in row:
        print(cell.value, end="  |  ")
    print()

By cell address

from openpyxl import load_workbook

wb = load_workbook("marks.xlsx")
ws = wb.active

print(ws['A1'].value)   # Header
print(ws['B2'].value)   # Marks of 2nd row

By Row

for row in ws.iter_rows(min_row=1, max_row=4, values_only=True):
    print(row)

By Column

for col in ws.iter_cols(min_col=1, max_col=2, values_only=True):
    print(col)

from openpyxl import load_workbook

wb = load_workbook("marks.xlsx")
ws = wb.active

ws['B3'] = 95  # Update marks for row 3
wb.save("marks.xlsx")

print("File updated")


Delete Sheet

wb = load_workbook("marks.xlsx")
del wb["Summary"]
wb.save("marks.xlsx")


from openpyxl.styles import Font

ws['A1'].font = Font(bold=True, size=12, color="FF0000")
ws['B1'].font = Font(bold=True, size=12)
wb.save("marks.xlsx")

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

data = [
    ["Name", "M1", "M2", "M3", "Total", "Average"],
    ["Raj", 85, 90, 88],
    ["Simran", 78, 82, 80],
]

for row in data:
    ws.append(row)

# Add formulas
ws['E2'] = "=B2+C2+D2"
ws['F2'] = "=E2/3"
ws['E3'] = "=B3+C3+D3"
ws['F3'] = "=E3/3"

wb.save("report.xlsx")
print("Report created!")

TaskMethod
Create fileWorkbook()
Load fileload_workbook()
Write cellws[‘A1’] = value
Append rowws.append()
Readws.rows, iter_rows()
FormattingFont()

Read Excel File

import openpyxl

def read_excel_file(file_path, sheet_name, cell_name):
# Load the workbook
workbook = openpyxl.load_workbook(file_path)
# Select the specified sheet
sheet = workbook[sheet_name]
# Read the value from the specified cell
cell_value = sheet[cell_name].value
print(f"Value in {cell_name} of sheet '{sheet_name}': {cell_value}")

# read one cell data
read_excel_file(file_path='users_data.xlsx', sheet_name='Sheet1', cell_name='A2')

Write Excel File

def write_excel_file(file_path, sheet_name, cell_name, data):
    # Load the workbook
    workbook = openpyxl.load_workbook(file_path)
    # Select the specified sheet
    sheet = workbook[sheet_name]
    # Write data to the specified cell
    sheet[cell_name] = data
    
    # Save the workbook
    workbook.save(file_path)
    print(f"Data written to sheet '{sheet_name}' starting at {cell_name}.")



write_excel_file(file_path='users_data.xlsx', sheet_name='Sheet1', cell_name='D2', data='Learning Excel with Python')

Variables Scope In Python

Variables declared inside a function are local to that function.


Variable declared outside a function can be accessed anywhere.


Use the global keyword to change it.


Inner function can access variable from the outer function.


The nonlocal keyword allows modifying a variable in the outer (enclosing) function.

Automation Practice Page

Text Fields





Radio Buttons



Checkboxes



Dropdown (Select)

Multi Select Dropdown

Buttons



JavaScript Alerts



File Upload

Date and Time Pickers





Links

Open Google
Go to Bottom

Web Table

ID Name Role
1 Deepesh Trainer
2 Rahul Tester
3 Anita Developer

Iframe

Hidden Element

Enabled & Disabled Fields



Image

Sample Image

Mouse Hover

Bottom of Page

This is the bottom of the page for scrolling practice.

Ultimate Automation Practice Page

Auto Suggestions (Google Style)

AJAX Success & Network Failure

Stale Element Simulation

Drag and Drop

Drag Me


Drop Here

Keyboard Actions

Nested Shadow DOM

Python Tuple

Introduction to Python Tuples

Python tuples are one of the core built-in data types that every Python programmer interacts with sooner or later. They look simple on the surface, yet they offer incredible power, speed, and reliability. If you’ve ever needed a collection that doesn’t change, tuples are your best friend. They’re lightweight, fast, and perfect for grouping related information.

A tuple is an ordered, immutable collection of elements. That means once a tuple is created, you cannot change its contents—no adding, deleting, or modifying individual items. This immutability makes tuples extremely efficient and safer for storing fixed data.

Syntax of Creating Tuples

my_tuple = (10, 20, 30)

# Yes, it's that simple.

Immutable Nature

Once created, you cannot modify a tuple. This allows Python to optimize performance behind the scenes.

Ordered and Indexed

A tuple maintains the order of elements. You can access items using indexes starting from 0.

Allow Duplicate Values

Unlike sets, tuples happily store repeated values.


Creating an Empty Tuple

empty_tuple = ()

Tuple with Multiple Data Types

mixed_tuple = (10, "hello", 3.14, True)

Single-Element Tuple

Here’s a common mistake:

not_a_tuple = (5)     # This is NOT a tuple
actual_tuple = (5,)   # This IS a tuple

nested_tuple = (1, 2, (3, 4, 5))

Using Indexing

Negative Indexing

print(colors[-1])  # blue

Accessing Nested Elements

nested = (1, (10, 20, 30), 3)
print(nested[1][1])  # 20

Basic Slicing

my_tuple = (0, 1, 2, 3, 4, 5)
print(my_tuple[1:4])  # (1, 2, 3)

Slicing with Steps

print(my_tuple[0:6:2])  # (0, 2, 4)

count(): Counts how many times a value appears.

nums = (1, 2, 2, 3)
print(nums.count(2))  # 2

index() : Returns the position of a value.

print(nums.index(3))  # 3

Concatenation

t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2)  # (1, 2, 3, 4)

Repetition

print(t1 * 3)  # (1, 2, 1, 2, 1, 2)

Membership Testing

print(2 in t1)  # True

Packing

packed = 10, 20, 30

Unpacking

a, b, c = packed

Using Asterisk Operator

a, *b = (1, 2, 3, 4, 5)
print(a)  # 1
print(b)  # [2, 3, 4, 5]

Using for Loop

for item in ("A", "B", "C"):
    print(item)

Using while Loop

i = 0
t = ("x", "y", "z")
while i < len(t):
    print(t[i])
    i += 1

There’s no actual “tuple comprehension,” but generator expressions behave similarly.

Example

gen = (x*x for x in range(5))
print(tuple(gen))  # (0, 1, 4, 9, 16)

Returning Multiple Values

def calc(a, b):
    return a+b, a*b

print(calc(3, 4))

numbers = (10, 20, 30, 40, 50)

print("First:", numbers[0])
print("Slice:", numbers[1:4])
print("Count of 20:", numbers.count(20))
print("Index of 30:", numbers.index(30))

Python String Methods

  1. len(): Returns the length of a string. Here’s an example:
# Using len() to get the length of a string
my_string = "Python Programming"

# Get the length of the string
length = len(my_string)

print("The length of the string is:", length) # Output: 18
  1. lower(): Converts all characters in a string to lowercase. Here’s an example:
# Using lower() to convert string to lowercase
my_string = "Python Programming"

# Convert the string to lowercase
lowercase_string = my_string.lower()

print("Original string:", my_string) # Output: Python Programming
print("Lowercase string:", lowercase_string) # Output: python programming
  1. upper(): Converts all characters in a string to uppercase. Here’s an example:
# Using upper() to convert string to uppercase
my_string = "Python Programming"

# Convert the string to uppercase
uppercase_string = my_string.upper()

print("Original string:", my_string) # Output: Python Programming
print("Uppercase string:", uppercase_string) # Output: PYTHON PROGRAMMING
  1. title(): Capitalizes the first character of each word in a string. Here’s an example:
# Using title() to capitalize the first character of each word
my_string = "python programming is fun"

# Convert the string to title case
title_string = my_string.title()

print("Original string:", my_string) # Output: python programming is fun
print("Title case string:", title_string) # Output: Python Programming Is Fun
  1. capitalize(): Capitalizes the first character of a string. Here’s an example:
# Using capitalize() to capitalize the first character of a string
my_string = "python programming"

# Capitalize the first character
capitalized_string = my_string.capitalize()

print("Original string:", my_string) # Output: python programming
print("Capitalized string:", capitalized_string) # Output: Python programming
  1. swapcase(): Swaps the case of all characters in a string. Here’s an example:
# Using swapcase() to swap the case of all characters in a string
my_string = "Python Programming"

# Swap the case of all characters
swapped_string = my_string.swapcase()

print("Original string:", my_string) # Output: Python Programming
print("Swapped case string:", swapped_string) # Output: pYTHON pROGRAMMING
  1. count(): Returns the number of occurrences of a substring in a string. Here’s an example:
# Using count() to count occurrences of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Count the occurrences of the word "Python"
count_python = my_string.count("Python")

print("Occurrences of 'Python':", count_python) # Output: 2
  1. find(): Returns the index of the first occurrence of a substring in a string. Here’s an example:
# Using find() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.find("Python")

print("Index of 'Python':", index_python) # Output: 0
  1. rfind(): Returns the index of the last occurrence of a substring in a string.
# Using rfind() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rfind("Python")

print("Index of the last 'Python':", last_index_python) # Output: 36

       10. index(): Like `find()`, but raises a `ValueError` if the substring is not found.

# Using index() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.index("Python")

print("Index of 'Python':", index_python) # Output: 0
  1. rindex(): Like `rfind()`, but raises a `ValueError` if the substring is not found.
# Using rindex() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rindex("Python")

print("Index of the last 'Python':", last_index_python) # Output: 36
  1. startswith(): Returns `True` if a string starts with a specified prefix, otherwise `False`.
# Using startswith() to check if the string starts with a specified prefix
my_string = "Python programming is fun."

# Check if the string starts with "Python"
starts_with_python = my_string.startswith("Python")

print("Starts with 'Python':", starts_with_python) # Output: True
  1. endswith(): Returns `True` if a string ends with a specified suffix, otherwise `False`.
# Using endswith() to check if the string ends with a specified suffix
my_string = "Python programming is fun."

# Check if the string ends with "fun."
ends_with_fun = my_string.endswith("fun.")

print("Ends with 'fun.':", ends_with_fun) # Output: True
  1. replace(): Replaces all occurrences of a substring with another substring.
# Using replace() to replace all occurrences of a substring
my_string = "Python is fun. Python is awesome."

# Replace "Python" with "Java"
new_string = my_string.replace("Python", "Java")

print("Original string:", my_string)
print("New string:", new_string)

       15. strip(): Removes whitespace (or other characters) from the beginning and end of a string.

  1. rstrip(): Removes whitespace (or other characters) from the end of a string.
# Using rstrip() to remove trailing whitespace
my_string = "Hello, world! "

# Remove the trailing whitespace
new_string = my_string.rstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. lstrip(): Removes whitespace (or other characters) from the beginning of a string.
# Using lstrip() to remove leading whitespace
my_string = " Hello, world!"

# Remove the leading whitespace
new_string = my_string.lstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. split(): Splits a string into a list of substrings using a specified delimiter.
# Using split() to split a string into a list of words
my_string = "Python is fun!"

# Split the string by whitespace (default behavior)
words = my_string.split()

print("List of words:", words)
  1. rsplit(): Splits a string from the right into a list of substrings using a specified delimiter.
# Using rsplit() to split a string from the right
my_string = "Python is fun and Python is awesome"

# Split the string by whitespace from the right
words = my_string.rsplit()

print("List of words:", words)

The separator used is the comma, which is passed as an argument to the rsplit() method. The 1 argument is used to specify that only one splitting should occur, which in this case splits the last fruit from the first two. Finally, we print the list of fruits.

       20. join(): Joins a list of strings into a single string using a specified delimiter.

# Joining with a space
words = ["Hello", "world", "Python", "rocks!"]
sentence = " ".join(words)
print(sentence) # Output: "Hello world Python rocks!"

# Joining with a comma
items = ["apple", "banana", "cherry"]
csv_line = ",".join(items)
print(csv_line) # Output: "apple,banana,cherry"

# Joining with a hyphen
letters = ["a", "b", "c", "d"]
hyphenated = "-".join(letters)
print(hyphenated) # Output: "a-b-c-d"
  1. isalnum(): Returns `True` if a string contains only alphanumeric characters, otherwise `False`.
# String with only letters and numbers
print("Hello123".isalnum()) # Output: True

# String with only letters
print("Python".isalnum()) # Output: True

# String with only numbers
print("2024".isalnum()) # Output: True

# String with a space
print("Hello World".isalnum()) # Output: False

# String with special characters
print("Hello@123".isalnum()) # Output: False

# Empty string
print("".isalnum()) # Output: False
  1. isalpha(): Returns `True` if a string contains only alphabetic characters, otherwise `False`.
# String with only letters
print("Python".isalpha()) # Output: True

# String with a space
print("Hello World".isalpha()) # Output: False

# String with numbers
print("Python3".isalpha()) # Output: False

# String with special characters
print("Hello!".isalpha()) # Output: False

# Empty string
print("".isalpha()) # Output: False
  1. isdigit() : Returns `True` if a string contains only digits; otherwise, `False`.
# String with only digits
print("12345".isdigit()) # Output: True

# String with letters
print("123abc".isdigit()) # Output: False

# String with a space
print("123 456".isdigit()) # Output: False

# Empty string
print("".isdigit()) # Output: False
  1. islower(): Returns `True` if all characters in a string are lowercase, otherwise `False`.
# All lowercase letters
print("hello".islower()) # Output: True

# Mixed case
print("Hello".islower()) # Output: False

# Digits and special characters are ignored
print("hello123!".islower()) # Output: True

# Contains an uppercase letter
print("helloWorld".islower()) # Output: False

# Empty string
print("".islower()) # Output: False

      25. isupper(): Returns `True` if all characters in a string are uppercase, otherwise `False`.

# All uppercase letters
print("HELLO".isupper()) # Output: True

# Mixed case
print("Hello".isupper()) # Output: False

# Includes digits and symbols
print("HELLO123!".isupper()) # Output: True

# Contains a lowercase letter
print("HELLOworld".isupper()) # Output: False

# Empty string
print("".isupper()) # Output: False
  1. istitle(): Returns `True` if a string is titlecased (i.e., the first character of each word is capitalized), otherwise `False`.
# Title-cased string
print("Hello World".istitle()) # Output: True

# Mixed case
print("Hello world".istitle()) # Output: False

# Uppercase string
print("HELLO WORLD".istitle()) # Output: False

# Lowercase string
print("hello world".istitle()) # Output: False

# Single title-cased word
print("Python".istitle()) # Output: True
  1. isspace(): Returns `True` if a string contains only whitespace characters, otherwise `False`.
# Only spaces
print(" ".isspace()) # Output: True

# Only tabs
print("\t\t".isspace()) # Output: True

# Newline characters
print("\n\n".isspace()) # Output: True

# Mixed whitespace characters
print(" \t\n".isspace()) # Output: True

# Empty string
print("".isspace()) # Output: False
  1. maketrans(): Creates a translation table to be used with the `translate()` function.
# Mapping characters 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
  1. translate(): Returns a copy of a string with specified characters replaced.
# Create a translation table to replace 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
  1. zfill(): Pads a numeric string with zeros on the left until the specified width is reached.
# Example using zfill() to pad a string with leading zeros
number = "42"
padded_number = number.zfill(5)

print(padded_number) # Output: '00042'
  1. expandtabs(): Replaces tabs in a string with spaces.
# Example using expandtabs() to replace tabs with spaces
text = "Hello\tWorld\tPython"
expanded_text = text.expandtabs(4) # Replaces tabs with 4 spaces

print(expanded_text)

# Output:
'Hello World Python'
  1. encode(): Encodes a string using a specified encoding.
# Encoding a string using UTF-8
my_string = "hello world"
encoded_string = my_string.encode("utf-8")

print(encoded_string) # Output: b'hello world'

  1. format_map(): Formats a string using a dictionary.
# Using format_map() to format a string using a dictionary
person = {"name": "Alice", "age": 30}

# Format string using the dictionary
formatted_string = "My name is {name} and I am {age} years old.".format_map(person)

print(formatted_string)
  1. isdecimal(): Returns `True` if a string contains only decimal characters, otherwise `False`.
# Using isdecimal() to check if a string contains only decimal characters
my_string = "12345"

# Check if the string contains only decimal characters
is_decimal = my_string.isdecimal()

print(is_decimal) # Output: True
  1. isnumeric(): Returns `True` if a string contains only numeric characters, otherwise `False`.
# Using isnumeric() to check if a string contains only numeric characters
my_string = "12345"

# Check if the string is numeric
is_numeric = my_string.isnumeric()

print(is_numeric) # Output: True
  1. partition(): It splits the string into parts based on the first occurrence of the substring.
# Using partition() to split a string based on the first occurrence of a substring
my_string = "Hello, world! Welcome to Python."

# Split the string at the first occurrence of ","
result = my_string.partition(",")

print(result)