🐍 Mastering Python Modules & File Handling: From Imports to Built-in Power Tools

Jugal kishoreJugal kishore
3 min read

As you level up in Python, one thing becomes clear β€” you don’t have to write everything from scratch! Python comes packed with modules that offer reusable code, tools, and utilities. Combine that with powerful file handling features, and you're ready to build real-world apps!

In this article, we’ll break down:

  1. 🧩 Understanding Python Modules: Creation, Import, and Renaming

  2. πŸ›  Exploring Essential Built-in Python Modules: datetime, math, os, and more

  3. πŸ“ Introduction to File Handling in Python: Opening and Managing Files


🧩 Understanding Python Modules: Creation, Import, and Renaming

πŸ“¦ What is a Python Module?

A module is simply a Python file (.py) that contains functions, classes, or variables which you can reuse in other Python scripts.


πŸ”Ή 1. Creating a Module

Let’s create a custom module named utils.py

# utils.py
def greet(name):
    return f"Hello, {name}!"

πŸ”Ή 2. Importing a Module

Now, use import to bring in your custom module.

import utils

print(utils.greet("Jugal"))

πŸ”Ή 3. Import Specific Functions

from utils import greet

print(greet("Kishore"))

πŸ”Ή 4. Renaming Modules

import utils as u

print(u.greet("Coder"))

βœ… Why use renaming?

  • To shorten names (numpy as np)

  • To avoid naming conflicts


πŸ›  Exploring Essential Built-in Python Modules

Python offers hundreds of built-in modules. Let’s explore the most essential ones for beginners:


πŸ—“ datetime β€” Work with Dates and Times

import datetime

now = datetime.datetime.now()
print("Current Date & Time:", now)

today = datetime.date.today()
print("Today’s Date:", today)

βž— math β€” Advanced Math Functions

import math

print(math.sqrt(16))      # Square root
print(math.factorial(5))  # 5!
print(math.pi)            # Ο€

πŸ—‚ os β€” Interact with the Operating System

import os

print("Current Directory:", os.getcwd())
print("Files in dir:", os.listdir())

# Create folder
os.mkdir("new_folder")

πŸ”„ random β€” Generate Random Numbers

import random

print(random.randint(1, 10))        # Random int between 1 and 10
print(random.choice(["red", "blue", "green"]))  # Random choice

πŸ“Š statistics β€” Basic Data Stats

import statistics

data = [1, 2, 3, 4, 5]
print("Mean:", statistics.mean(data))
print("Median:", statistics.median(data))

πŸ“ Introduction to File Handling in Python: Opening and Managing Files

Python makes it super easy to read from and write to files β€” great for building apps that handle data.


πŸ”Ή Opening a File

f = open("example.txt", "r")
print(f.read())
f.close()

πŸ”Ή Writing to a File

f = open("example.txt", "w")
f.write("Hello, world!")
f.close()

πŸ”Ή Reading Line-by-Line

f = open("example.txt", "r")
for line in f:
    print(line.strip())
f.close()

πŸ”Ή Using with Statement (Best Practice)

Automatically handles closing the file.

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

πŸ”Ή Append Mode

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

πŸ“Œ Summary Table

FeatureExample Used
Module Creationutils.py with greet() function
Built-in Moduledatetime, math, os, random
File HandlingReading, writing, appending files

πŸš€ Conclusion

Python's modular system and file handling capabilities make it a powerhouse for developers. By using custom and built-in modules, you reduce redundancy. With file I/O, your scripts can persist and manage data like a pro.

βœ… Practice creating your own modules
βœ… Explore built-in Python power tools
βœ… Use file handling to build data-driven apps

0
Subscribe to my newsletter

Read articles from Jugal kishore directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jugal kishore
Jugal kishore