Writing Logic and Functions
Modules, Libraries, and File I/O
9 min read
Don't reinvent the wheel
One of Python's great strengths is that most common tasks have already been solved — by other developers, packaged into reusable code, and made freely available.
Modules and libraries let you import that pre-written code into your own programs. And File I/O (input/output) lets your programs save data to a file or load data from one — so your work isn't lost when the program closes.
This lesson covers both.
What is a module?
A module is a Python file containing reusable code — functions, variables, and more. Python ships with dozens of built-in modules as part of its standard library (the collection of modules that comes with every Python installation).
To use a module, you import it at the top of your file:
import math
print("Square root of 16:", math.sqrt(16)) # 4.0
print("Value of pi:", math.pi) # 3.141592653589793
print("Ceiling of 4.3:", math.ceil(4.3)) # 5
print("Floor of 4.9:", math.floor(4.9)) # 4
The math module gives you access to mathematical functions and constants that Python doesn't include by default.
Commonly used standard library modules
Python's standard library covers an enormous range of tasks:
| Module | What it does |
|---|---|
math | Mathematical functions: square root, trigonometry, logarithms, pi |
random | Random number generation, shuffling, sampling |
datetime | Working with dates, times, and time intervals |
os | Interacting with the operating system (files, directories, env vars) |
json | Reading and writing JSON data |
csv | Reading and writing CSV spreadsheet files |
re | Regular expressions for advanced text pattern matching |
The random module
import random
print(random.randint(1, 100)) # random integer from 1 to 100
print(random.choice(["rock", "paper", "scissors"])) # pick one randomly
deck = ["Ace", "2", "3", "4", "5"]
random.shuffle(deck)
print("Shuffled deck:", deck)
Real-world use: password generation, games, A/B test assignment, random sampling.
The datetime module
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
print("Year:", now.year)
print("Month:", now.month)
print("Today's date:", now.strftime("%B %d, %Y")) # July 01, 2026
Real-world use: log timestamps, calculate deadlines, schedule reminders.
Importing just what you need
Instead of importing a whole module, you can import specific functions:
from math import sqrt, pi
print(sqrt(25)) # 5.0 — no need to write math.sqrt()
print(pi) # 3.141592653589793
This keeps your code shorter, especially when you only need one or two things from a large module.
File I/O: reading and writing files
Your programs can save data to files and load it back later. This is how programs persist information between runs — without it, everything resets every time the program closes.
Python uses the built-in open() function for file operations.
Writing to a file
with open("log.txt", "w") as file:
file.write("Python basics notebook log\n")
file.write("Lesson completed successfully.\n")
"log.txt"— the filename to create or overwrite"w"— write mode (creates the file; overwrites it if it already exists)as file— the variable name you use to interact with the file inside the block\n— a newline character (moves to the next line)- The
withstatement automatically closes the file when the block ends — no need to close it manually
Reading from a file
with open("log.txt", "r") as file:
content = file.read()
print("File content:\n", content)
"r"— read mode (opens an existing file).read()reads the entire file content as one string
Appending to an existing file
with open("log.txt", "a") as file:
file.write("Another entry added.\n")
"a"— append mode (adds to the end of an existing file without overwriting it)
File mode quick reference
| Mode | Meaning |
|---|---|
"r" | Read an existing file. The pointer starts at the beginning. This is the default mode. |
"w" | Write to a file. Creates it if it doesn't exist; overwrites it if it does. |
"a" | Append to a file. The pointer starts at the end, so writes add on without erasing what's there. |
"r+" | Read and write. The pointer starts at the beginning. |
"w+" | Write and read. Overwrites the file if it exists, same as "w". |
"a+" | Append and read. The pointer starts at the end, same as "a". |
A filename can be a relative path ("log.txt" — looked up in the directory the program runs from) or an absolute path ("/Users/you/data/log.txt" on macOS/Linux, "C:\\Users\\you\\data\\log.txt" on Windows).
The methods of a file object
open() gives you back a file object, and that object has several methods for reading and writing. Picking the right one depends on how much of the file you want at a time.
read(size) — read the whole file, or a chunk of it
with open("log.txt", "r") as file:
print(file.read()) # entire file as one string
Pass a number to read() and it reads only that many characters instead of the whole file — useful for very large files where loading everything at once would use too much memory:
with open("log.txt", "r") as file:
print(file.read(10)) # just the first 10 characters
If the file pointer is already at the end, read() returns an empty string ("") rather than raising an error — that's how you can detect "nothing left to read."
readline() — read one line at a time
with open("log.txt", "r") as file:
print(file.readline()) # just the first line, including its "\n"
Each call to readline() moves the pointer forward, so calling it again returns the next line. An empty string means you've reached the end of the file.
readlines() — read every line into a list
with open("log.txt", "r") as file:
lines = file.readlines()
print(lines)
# ['Python basics notebook log\n', 'Lesson completed successfully.\n']
for line in lines:
print(line.strip())
readlines() loads the whole file at once, same as read(), but splits it into a list of lines instead of one long string — handy when you need to loop over lines, count them, or index into a specific one.
Reading a file line by line without loading it all
For very large files, looping directly over the file object is more memory-efficient than readlines(), since it reads one line at a time instead of the whole file:
with open("log.txt", "r") as file:
for line in file:
print(line.strip()) # .strip() removes the trailing newline
Jumping around a file: seek() and tell()
Every open file has a file pointer — a running position that tracks where the next read or write will happen. read(), readline(), and write() all move it forward automatically. Two methods let you inspect and control it directly:
f.tell()— returns the pointer's current position, as a byte offset from the start of the filef.seek(offset)— moves the pointer to a specific offset, measured from the beginning of the file by default
Diagram — How seek() and tell() Move the File Pointer
with open("wonderland.txt", "r") as file:
file.seek(7) # jump to the 8th character (offset 7)
print(file.readline()) # reads from there to the end of the line
print(file.tell()) # reports the pointer's new position
Output:
ul is better than ugly.
31
seek() is what makes it possible to re-read part of a file without closing and reopening it, or to jump straight to a known position (like the start of a record in a fixed-format file) instead of reading everything before it.
A complete example: log file
Here's the full pattern from the workbook — write a log file, then read it back:
import math
print("Square root of 16:", math.sqrt(16))
# Write a small log file
with open("example_log.txt", "w") as file:
file.write("Python basics notebook log\n")
file.write("Lesson completed successfully.\n")
# Read the file back
with open("example_log.txt", "r") as file:
content = file.read()
print("File content:\n", content)
Output:
Square root of 16: 4.0
File content:
Python basics notebook log
Lesson completed successfully.
Installing third-party libraries with pip
The standard library is impressive, but the real power comes from third-party libraries — code built by the Python community and installable with pip:
pip install pandas # data analysis
pip install matplotlib # charts and graphs
pip install requests # making web requests
pip install flask # building web apps
Once installed, you import them just like standard library modules:
import pandas as pd
import matplotlib.pyplot as plt
These libraries are what take Python from a scripting language to a professional tool for data science, AI, and web development.
Next steps
You've now covered the core building blocks of Python:
- Variables and data types — storing information
- Strings — working with text
- Lists, tuples, dictionaries — organizing collections
- Control flow — making decisions
- Loops — repeating actions
- Functions — packaging reusable logic
- Modules and file I/O — extending Python and saving data
Two more tools round out this foundation: list comprehensions give you a faster, more readable way to build lists than a raw for loop, and exception handling lets your programs recover from runtime errors — like a missing file — instead of crashing.
The best way to consolidate all of it is to build something. A few starter ideas from the workbook:
- Student grade tracker — take a list of scores, compute averages, assign letter grades, save a report to a file
- Shopping calculator — maintain a list of items and prices, compute a total with tax, print a receipt
- Random quiz generator — store questions and answers in a dictionary, shuffle them randomly, ask the user and track their score
Key takeaway
Modules let you import pre-written code so you don't have to write everything from scratch. Python's standard library covers math, dates, random numbers, file handling, and much more. File I/O lets your programs save and load data between runs: open() sets the mode ("r", "w", "a", or their + variants), read() / readline() / readlines() pull data out, write() pushes it in, and seek() / tell() let you control exactly where in the file you're reading from or writing to. Third-party libraries installed via pip extend Python's reach into data science, AI, web development, and beyond.