惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
Blog — PlanetScale
Blog — PlanetScale
Vercel News
Vercel News
L
LangChain Blog
Google DeepMind News
Google DeepMind News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
D
DataBreaches.Net
云风的 BLOG
云风的 BLOG
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
About on SuperTechFans
博客园_首页
N
Netflix TechBlog - Medium
Y
Y Combinator Blog
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
Apple Machine Learning Research
Apple Machine Learning Research
罗磊的独立博客
美团技术团队
V
V2EX

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Python for Beginners — Part 7: Modules, Errors & Files
Ramesh S · 2026-06-23 · via DEV Community

Part 7 of a beginner-friendly series on learning Python from scratch.

In Part 6, we learned to write reusable functions. Now it's time to make those functions work in the real world: reading data from files, handling things when they go wrong, and using code other people have written.

This is where Python transitions from "learning exercises" to "actual programs." Real programs read files, talk to the internet, handle unexpected input, and use libraries to solve complex problems.

Modules and Imports

A module is a file containing Python code that you can reuse. Python comes with a huge standard library of modules, and you can also install external ones.

Using the math module

import math

print(math.sqrt(16))      # 4.0
print(math.pow(2, 3))     # 8.0
print(math.pi)            # 3.14159...
print(math.ceil(4.3))     # 5 (round up)
print(math.floor(4.7))    # 4 (round down)

import math loads the math module. You access its functions and constants with dot notation: math.sqrt(), math.pi, etc.

Importing specific items

If you only need a few things, import them directly:

from math import sqrt, pi

print(sqrt(16))   # 4.0 (no need for math.)
print(pi)         # 3.14159...

Now you use sqrt() directly, not math.sqrt().

Aliasing imports

Use as to give a module a shorter name:

import math as m

print(m.sqrt(16))  # 4.0

Or alias specific items:

from math import sqrt as square_root

print(square_root(16))  # 4.0

Working with datetime

The datetime module is essential for handling dates and times:

from datetime import datetime, timedelta

# Get current date and time
now = datetime.now()
print(now)  # 2024-06-23 14:30:45.123456

# Create a specific date
birthday = datetime(1999, 5, 15)
print(birthday)  # 1999-05-15 00:00:00

# Format as string
print(now.strftime("%Y-%m-%d"))  # 2024-06-23
print(now.strftime("%A, %B %d"))  # Sunday, June 23

# Time differences
future = now + timedelta(days=30)
print(future)  # Date 30 days from now

Working with JSON

JSON (JavaScript Object Notation) is a standard format for exchanging data. Python dictionaries map perfectly to JSON:

import json

# Convert Python dict to JSON string
person = {
    "name": "Ramesh",
    "age": 25,
    "city": "Chennai",
    "hobbies": ["reading", "coding", "gaming"]
}

json_string = json.dumps(person)
print(json_string)
# {"name": "Ramesh", "age": 25, "city": "Chennai", "hobbies": ["reading", "coding", "gaming"]}

# Convert JSON string back to Python dict
parsed = json.loads(json_string)
print(parsed["name"])  # Ramesh

Reading and writing JSON files:

import json

# Write to file
data = {"name": "Ramesh", "age": 25}
with open("data.json", "w") as file:
    json.dump(data, file)

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

Regular Expressions (Regex)

Regex is a language for pattern matching in text. It's powerful but takes time to master. Here are common patterns:

import re

text = "My phone is 555-1234 and email is user@example.com"

# Find a pattern
phone = re.search(r"\d{3}-\d{4}", text)
if phone:
    print(phone.group())  # 555-1234

# Find all matches
emails = re.findall(r"[\w.-]+@[\w.-]+\.\w+", text)
print(emails)  # ['user@example.com']

# Replace
cleaned = re.sub(r"\d", "X", text)
print(cleaned)  # Phone is XXX-XXXX...

# Check if pattern matches
if re.match(r"^\d+$", "12345"):
    print("It's all digits")

Regex patterns (a few common ones):

  • \d — any digit (0-9)
  • \w — any word character (letter, digit, underscore)
  • \s — any whitespace
  • . — any character
  • * — zero or more
  • + — one or more
  • ? — zero or one
  • {n} — exactly n times
  • ^ — start of string
  • $ — end of string
  • [abc] — a, b, or c

Regex is complex; this is just an introduction. Most beginners use regex sparingly and look up patterns when needed.

File Input and Output

Reading files

# Simple read
with open("myfile.txt", "r") as file:
    content = file.read()
    print(content)

# Read line by line
with open("myfile.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes newline

# Read all lines as a list
with open("myfile.txt", "r") as file:
    lines = file.readlines()
    print(lines[0])  # First line

The with statement is crucial — it automatically closes the file when you're done, even if an error occurs.

Writing files

# Write (overwrites if file exists)
with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("Second line\n")

# Append (add to end of file)
with open("output.txt", "a") as file:
    file.write("Third line\n")

Working with file paths

import os

# Check if file exists
if os.path.exists("myfile.txt"):
    print("File found")

# Get file size
size = os.path.getsize("myfile.txt")
print(f"File size: {size} bytes")

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

# Create directory
os.makedirs("my_folder", exist_ok=True)

# Delete file
os.remove("myfile.txt")

Exception Handling

Real programs fail sometimes — bad file paths, network errors, invalid input. Handle these gracefully with try/except:

try:
    # Code that might fail
    number = int("not a number")
except ValueError:
    print("That's not a valid number")

If int() fails, Python catches the ValueError and runs the except block instead of crashing.

Multiple exceptions

try:
    file = open("missing.txt", "r")
    number = int(file.read())
except FileNotFoundError:
    print("File doesn't exist")
except ValueError:
    print("File contains non-numeric data")
except Exception as e:
    print(f"Something went wrong: {e}")

Handle specific errors first, then generic ones. Exception catches everything.

Try, except, else, finally

try:
    file = open("data.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found")
else:
    # Runs if no exception occurred
    print(f"Successfully read {len(data)} characters")
finally:
    # Always runs, useful for cleanup
    print("Done")

  • try — code that might fail
  • except — what to do if it fails
  • else — what to do if it succeeds
  • finally — always runs (cleanup)

Raising exceptions

You can raise exceptions yourself:

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age > 150:
        raise ValueError("Age seems unrealistic")
    return True

try:
    validate_age(-5)
except ValueError as e:
    print(f"Invalid input: {e}")

Installing External Libraries with pip

The pip package manager lets you install libraries others have written:

pip install requests      # Install the requests library
pip install numpy pandas  # Install multiple packages
pip install requests==2.28.0  # Install specific version
pip list                  # Show installed packages
pip uninstall requests    # Remove a package

Once installed, use them like built-in modules:

import requests

response = requests.get("https://api.github.com")
print(response.status_code)  # 200

Popular libraries for beginners:

  • requests — make web requests
  • numpy — numerical computing
  • pandas — data analysis
  • matplotlib — plotting and visualization
  • flask — build web applications

Practical Examples

Example 1: Read and count words

def count_words(filename):
    try:
        with open(filename, "r") as file:
            content = file.read()
            words = content.split()
            return len(words)
    except FileNotFoundError:
        print(f"Error: {filename} not found")
        return 0

count = count_words("myfile.txt")
print(f"Total words: {count}")

Example 2: Save and load JSON data

import json

def save_contacts(contacts, filename):
    with open(filename, "w") as file:
        json.dump(contacts, file, indent=2)

def load_contacts(filename):
    try:
        with open(filename, "r") as file:
            return json.load(file)
    except FileNotFoundError:
        return []

# Save
contacts = [
    {"name": "Ramesh", "phone": "555-1234"},
    {"name": "Priya", "phone": "555-5678"}
]
save_contacts(contacts, "contacts.json")

# Load
loaded = load_contacts("contacts.json")
print(loaded)

Example 3: Extract data with regex

import re

def extract_emails(text):
    pattern = r"[\w.-]+@[\w.-]+\.\w+"
    return re.findall(pattern, text)

text = "Contact me at john@example.com or jane.doe@company.co.uk"
emails = extract_emails(text)
print(emails)  # ['john@example.com', 'jane.doe@company.co.uk']

Why This Matters

File I/O and exception handling are what separate learning exercises from real programs. Every professional program reads data from files or the internet, handles errors gracefully, and uses external libraries. Modules let you leverage thousands of hours of other people's work instead of writing everything yourself.

The most common beginner mistakes:

  • Forgetting to close files (use with — it's mandatory style)
  • Not handling file not found errors
  • Assuming regex patterns are simpler than they are
  • Catching generic Exception instead of specific errors
  • Not installing libraries with pip correctly

What's Next

In Part 8, the final part, we'll explore object-oriented programming — classes, inheritance, and polymorphism. OOP is how professional Python code is structured, and everything you've learned so far will come together.


This is Part 7 of an 8-part beginner Python series. Catch up on Part 1: Getting Started & Syntax, Part 2: Variables, Data Types & Numbers, Part 3: Strings & Booleans, Part 4: Operators & Control Flow, Part 5: Collections, and Part 6: Functions.