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

推荐订阅源

Google DeepMind News
Google DeepMind News
博客园_首页
H
Help Net Security
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
GbyAI
GbyAI
Scott Helme
Scott Helme
D
Docker
Hacker News: Ask HN
Hacker News: Ask HN
P
Privacy & Cybersecurity Law Blog
Jina AI
Jina AI
雷峰网
雷峰网
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
G
GRAHAM CLULEY
C
Cisco Blogs
The Hacker News
The Hacker News
F
Full Disclosure
Y
Y Combinator Blog
Blog — PlanetScale
Blog — PlanetScale
Recent Announcements
Recent Announcements
G
Google Developers Blog
量子位
K
Kaspersky official blog
Cisco Talos Blog
Cisco Talos Blog
The Cloudflare Blog
A
About on SuperTechFans
C
Cybersecurity and Infrastructure Security Agency CISA
Last Week in AI
Last Week in AI
博客园 - 三生石上(FineUI控件)
Microsoft Security Blog
Microsoft Security Blog
Martin Fowler
Martin Fowler
T
Tenable Blog
P
Palo Alto Networks Blog
H
Heimdal Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Schneier on Security
Schneier on Security
The Register - Security
The Register - Security
F
Fortinet All Blogs
Stack Overflow Blog
Stack Overflow Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
The Blog of Author Tim Ferriss
N
News and Events Feed by Topic
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
What I Learned in Week 4 of Python — Files, Real Programs & My First Class
Om Kolhapure · 2026-06-01 · via DEV Community

Week 4 had a different energy.

The programs stopped feeling like exercises and started feeling like tools I'd actually use. A note-taking app that persists files to disk. An expense tracker that exports to CSV. A finance tracker that generates monthly reports. And then — at the very end — rewriting that finance tracker using a class for the first time.

One month of Python. Here's how Week 4 went.


Day 22 — File I/O: A Note-Taking App

The note-taking app was the first project I built where I genuinely thought: I would actually use this.

CRUD — Create, Read, Update, Delete — all persisted to real .txt files on disk. Title becomes filename. Notes survive after the program closes. The whole thing hinges on two small helper functions that every other function calls:

import sys
import os

def main():
    print("\tWelcome to notes\n")
    while True:
        print("What would you like to do?")
        while True:
            user_response = input("1.Add a new note\n2.view a note\n3.update a note\n4.Delete a note\n Press 'q' to quit\n-> ")
            if user_response in ("1", "2", "3", "4", "q"):
                break
        match user_response:
            case "1":
                add_note()
            case "2":
                if read_notes().strip() == "":
                    print("No note found, try adding a note first!")
                else:
                    view_note()
            case "3":
                if read_notes().strip() == "":
                    print("No note found, try adding a note first!")
                else:
                    update_note()
            case "4":
                if read_notes().strip() == "":
                    print("No note found, try adding a note first!")
                else:
                    delete_note()
            case "q":
                sys.exit()


def add_note():
    '''Creates a new txt file and asks user for title as the name of file and content of the file'''
    usr_title = input("Enter title: "\").strip().title()"
    if usr_title in read_notes():
        print("File Already exists")
    else:
        store_notes(usr_title)
        usr_content = input("Write here:\n")
        with open(f"{usr_title}.txt", "w") as file:
            file.write(usr_content)
            print("Saved")
        print(read_notes())

def view_note():
    '''Displays existing notes to the user and asks the user to select a note to read'''
    print(read_notes())
    usr_note = input("Enter the name of the note you want to view: ").strip().title()
    if usr_note in read_notes():
        with open(f"{usr_note}.txt") as file:
            print(file.read())
    else:
        print("Note not found!")


def update_note():
    '''Displays the saved notes to the user and asks user for the file and the content to update'''
    print(read_notes())
    select_note = input("Enter the name of the note you want to update: ").strip().title()
    if select_note in read_notes():

        with open(f"{select_note}.txt") as f_ile:
            print(f_ile.read())
        new_content = input("Write new text here:\n")    
        with open(f"{select_note}.txt", "a") as file:
            file.write(f"\n{new_content}")
            print("saved")
        with open(f"{select_note}.txt") as f:
            print(f.read())
    else:
        print("Note not found!")


def delete_note():
    '''Displays notes to the user and asks him to enter the name of a note user wants to delete'''
    print(read_notes())
    del_note = input("Enter the name of the note you want to delete: ").strip().title()
    if del_note in read_notes():
       os.remove(f"{del_note}.txt")
    else:
        print("Note not found!")


def store_notes(note):
    '''Stores the title of the note provided by the user to keep track of notes'''
    with open("notes.txt", "a") as app_file:
        app_file.write(f"{note}\n")


def read_notes():
    with open("notes.txt") as app_file:
        return app_file.read()

if __name__ == "__main__":
    main()

Three things I'm proud of here:

  • store_notes() and read_notes() act as a lightweight index. Every note title gets written to notes.txt so the app always knows what files exist without scanning the directory.
  • Guard checks before every operationif read_notes().strip() == "": in main() catches the "no notes yet" case cleanly before passing control to any function.
  • if __name__ == "__main__": — this is the first time I used it properly. It means the app only runs when executed directly, not when imported as a module. A small habit that makes code more reusable.

Day 23 — CSV Handling: An Expense Tracker

Day 23 was about the csv module — Python's built-in tool for reading and writing spreadsheet-compatible files. I built an expense tracker that writes to a named CSV file, reads it back, and deletes rows:

import csv
import sys
import os


def main():
    print("\n\tWelcome to expense tracker!")
    print("What would you like to do?")
    main_file = tracker_file()
    while True:
        user_response = input("1.Add expense\n2.View expenses\n3.Delete an expense\nEnter 'q' to quit\n-> ")
        if user_response in ("1", "2", "3", "q"):   
            match user_response:
                case "1":
                    add_expense(main_file)
                case "2":
                    view_expense(main_file)
                case "3":
                    delete_expense(main_file)
                case "q":
                    sys.exit()

def tracker_file():
    file_name = input("Enter the file name you want to save your expenses into: ").strip().title()
    if os.path.isfile(f"{file_name}.csv"):
        print("File Already exists")
    else:
        with open(f"{file_name}.csv", "a") as expense_file:
            column_title = csv.writer(expense_file)
            column_title.writerow(["Category","Expense"])
    return f"{file_name}.csv"

def add_expense(main_file):
    '''Adds expense category to the csv file in category column and expense in expense column'''
    while True:
        user_category = input("Enter the category of the expense: ").strip().title()
        user_expense = input("Enter your expense: ").strip()
        if user_category.isspace() or user_expense.isspace():
            print("The field cannot be empty")
        elif user_category.isdecimal() or user_expense.isalpha():
            print("Category takes the category of expense!")
            print("Expense takes the expense on the category!")
        else:
            break
    with open(main_file, "a", newline = "") as add_file:
        adder = csv.DictWriter(add_file, fieldnames = ["Category", "Expense"], lineterminator = "\n")
        adder.writerow({"Category": user_category, "Expense": user_expense})

def view_expense(main_file):
    '''Shows the user his expenses'''
    if os.path.isfile(main_file):
        with open(main_file) as view_file:
            viewer = csv.DictReader(view_file)
            for row in viewer:
                print(f"{row['Category']}:- {row['Expense']}")
    else:
        print("No file found!")


def delete_expense(main_file):
    view_expense(main_file)
    if os.path.isfile(main_file):
        ask_user = input("\nEnter the category of the expense you want to delete: ").strip().title()
        with open(main_file) as del_file:
            reader = list(csv.reader(del_file))
            for row in reader:
                if ask_user in row:
                    reader.remove(row)
                else:
                    print("Category not found!")
        with open(main_file, "w", newline = "") as deleted_file:
            writer = csv.writer(deleted_file, lineterminator = "\n")
            writer.writerows(reader)
        print("Deleted")
    else:
        print("No file found!")


if __name__ == "__main__":
    main()

The delete_expense() function taught me the standard pattern for editing a CSV: read everything into memory as a list, remove the unwanted row, then write the whole list back. You can't surgically remove a line from a CSV file — you rewrite the whole thing. Once you know that, the pattern makes complete sense.

csv.DictWriter and csv.DictReader were the real discovery here — working with rows as dictionaries (row['Category']) instead of indexes (row[0]) makes the code read like the data it represents.


Day 24 — JSON & Data Persistence

Day 24 was about json — specifically using it as a lightweight database. The insight: JSON is just a string format for Python dictionaries. json.dumps() converts a dictionary to a string you can write to a file. json.loads() converts it back.

This pattern became the backbone of the finance tracker (Day 26) — every transaction is stored as a JSON line in report.txt, one dictionary per line. Reading it back is just a loop over file.readlines() with json.loads() on each line.

Writing structured data as JSON instead of plain text means you can store a full dictionary — date, type, category, amount, description — in a single line and retrieve it perfectly. No parsing, no splitting on commas, no guessing field positions.


Day 25 — Regular Expressions

Regex was the topic I'd been most nervous about. The syntax looks like a password generator exploded. But once I slowed down and built two programs to apply it, the logic clicked.

Email Validator

import re 

def main():
    user_email = input("Enter your email: ").strip()
    email_validator(user_email)


def email_validator(email):
    if re.fullmatch(r"\w+@(\w+\.)?\w+\.\w{3}", email, re.IGNORECASE):
        print("Valid")
    else:
        print("Invalid")

if __name__ == "__main__":
    main()

Then I went further and built a more robust version using the email-validator library:

from email_validator import validate_email, EmailNotValidError
mail = input("Enter your email: ").strip()
try:
    validate_email(mail)
    print("Valid Email")
except EmailNotValidError:
    print("Invalid Email")

Two approaches, two lessons: regex gives you control and portability; a dedicated library gives you correctness out of the box. Both have their place.

Log Parser

The log parser was where regex went from "I understand this" to "I can actually use this":

import re
ip_re = r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*(\[\d{2}/[a-z^hikwxz]{3}/\d{4}:\d{2}:\d{2}:\d{2} [+-]{1}\d{4}\])"
with open("access.log") as log_file:
    contents = log_file.read()
match = re.findall(ip_re, contents, re.IGNORECASE)
for required_value in match:
    print(f"IP address: {required_value[0]} | Timestamp: {required_value[1]}")

That single pattern extracts both the IP address and the timestamp from every line of a server log file. re.findall() returns a list of tuples — each tuple is one match, with group 1 (IP) and group 2 (timestamp) as elements.

The [a-z^hikwxz]{3} part matches a three-letter month abbreviation while excluding letters that don't appear in any month name. That kind of precision in a pattern is what makes regex so powerful — and so worth learning.


Day 26 — The Mini-Project: Personal Finance Tracker

Day 26 brought everything together: file I/O, JSON persistence, CSV export, regex date validation, and a clean menu-driven architecture. This is the most complete program I've built.

Features:

  • 💰 Add income and expense transactions with date, category, amount, description
  • 📊 View a monthly report — income, expenses, net balance — filtered by month
  • 📁 Export any month's report to a formatted CSV file
  • 🗑️ Delete individual transactions or entire reports
  • ✅ Regex validates every date before it's saved
import csv
import json
import os
import re
import sys

def main():
    '''Main function'''
    print("===Personal Finance Tracker===")
    print("What would youy like to do?")
    print("SELECT THE CORRESPONDING NUMBER FOR THE GIVEN OPREATION")
    while True:
        while True:
            usr_response = input("1. Add Transaction\n2. View Monthly Report\n3. Export Report To CSV\n4.Delete Transaction\n5.Delete Report\n6.Exit\n--> ").strip()
            if usr_response in ("1", "2", "3", "4", "5", "6"):
                break
        match usr_response:
            case "1":
                add_transaction()
            case "2":
                view_report()
            case "3":
                export_report()
            case "4":
                delete_trans()
            case "5":
                delete_report()
            case "6":
                sys.exit()


def add_transaction():
    '''Adds the user transaction to a file as a dictionary'''
    while True:
        input_date = input("Enter the transaction date(dd/mm/yyyy): ").strip()
        if re.search(r"^\d{1,2}/ ?\d{1,2}/ ?\d{4}$", input_date):
            trans_date = input_date
            break
        else:
            print("Enter date in dd/mm/yyyy format!")
    while True:
        trans_type = input("Is it income or expense? ").strip().lower()
        if trans_type in ("income", "expense"):
            break

    trans_category = input("Enter the category you did the transaction for: ").strip().title()

    while True:
        try:
            trans_amount = float(input("Enter transaction amount: ").strip())
            break
        except ValueError:
            print("Enter the numbers!")

    while True:
        ask_user = input("Do you want to add a description[Y/N]? ").strip().upper()
        if ask_user in ("Y", "N"):
            break
    if ask_user == "Y":
        trans_descrp = input("Enter transaction description\n--> ")
    else:
        trans_descrp = None

    transaction = {"date": trans_date, "type": trans_type, "category": trans_category, "amount": trans_amount, "description": trans_descrp}
    with open("report.txt", "a") as report_file:
        report_file.write(f"{json.dumps(transaction)}\n")


def view_report():
    '''Shows monthy income and monthly expense and net balance and returns the user input'''
    view_income = []
    view_expense = []
    total_income = 0
    total_expense = 0
    while True:
        view_month = input("Enter the month and year of the transaction(mm/yyyy): ").strip()
        if re.search(r"^\d{1,2}/ ?\d{4}$", view_month):
            break
        else:
            print("Enter in the mm/yyyy format!")
    with open("report.txt") as view_file:
        lines = view_file.readlines()
        if not lines:
            print("No Transactions To View!")
        else:
            for trans_dict in lines:
                view_dict = json.loads(trans_dict)
                if view_month == re.search(r"^\d{1,2}/ ?(\d{1,2}/ ?\d{4})$", view_dict['date']).group(1):
                    if view_dict['type'] == "income":
                        view_income.append(f"\t{view_dict['category']}: {view_dict['amount']}\n")
                        total_income += view_dict['amount']
                    else:
                        view_expense.append(f"\t{view_dict['category']}: {view_dict['amount']}\n")
                        total_expense += view_dict['amount']

                    print(f"===REPORT FOR {view_month}===")
                    for income_trans in view_income:
                        print("Income:")
                        print(income_trans)
                    print(f"Total Income: ${total_income}")
                    for expense_trans in view_expense:
                        print("Expenses: ")
                        print(expense_trans)
                    print(f"Total Expenses: ${total_expense}\n")
                    print(f"Net Balance: ${total_income - total_expense}")
    return view_month, total_income, total_expense


def export_report():
    '''Exports monthly report to csv'''
    trans_month, total_income, total_expense = view_report()
    safe_month = trans_month.replace("/", "_")
    if total_income == 0 and total_expense == 0:
        print("No Transactions to Export!")
    else:
        if os.path.isfile(f"Report_{safe_month}.csv"):
            print("Report already exported!")
        else:
            with open(f"Report_{safe_month}.csv", "a", newline = "") as export_file:
                writer = csv.DictWriter(export_file, fieldnames = ["Type", "Category", "Description", "Amount"], lineterminator = "\n")
                writer.writeheader()
                with open("report.txt") as info_file:
                    for info_dict in info_file.readlines():
                        new_dict = json.loads(info_dict)
                        if trans_month == re.search(r"^\d{1,2}/ ?(\d{1,2}/ ?\d{4})$", new_dict['date']).group(1):
                            writer.writerow({'Type': new_dict['type'], 'Category': new_dict['category'], 'Description': new_dict['description'], 'Amount': new_dict['amount']})

                total_writer = csv.writer(export_file, lineterminator = "\n")
                total_writer.writerows([[None, None, "Total Income", total_income],
                                        [None, None, "Total Expense", total_expense],
                                        [None, None, "Net Balance", total_income - total_expense]])    


def delete_trans():
    delete_cat = input("Enter category of the transaction you want to delete: ").strip()
    delete_date = input("Enter the date of the transaction you want to delete(dd/mm/yyyy)")
    remaining_trans = []
    if os.path.isfile("report.txt"):
        with open("report.txt") as del_file:
            trans_lines = del_file.readlines()
            for trans_line in trans_lines:
                Dict = json.loads(trans_line)
                if delete_cat not in Dict.values() and delete_date not in Dict.values():
                    remaining_trans.append(Dict)

        with open("report.txt", "W") as new_file:
            for data in remaining_trans:
                new_file.write(f"{json.dumps(data)}\n")
    else:
        print("No transaction to delete try adding a transaction!")

def delete_report():
    ask_report = input("Enter the name of the report you want to delete: ")
    if os.path.isfile(f"{ask_report}.csv"):
        os.remove(f"{ask_report}.csv")
    else:
        print("NO Report Found With The Given Name")

if __name__ == "__main__":
    main()

The export_report() function was the most satisfying to get working. It calls view_report() first to get the month and totals, then writes every matching transaction as a CSV row, and appends summary rows at the end. Open the exported file in Excel and it's a clean, formatted monthly report.

Regex appears three times in this program — validating the transaction date on input, validating the month filter, and extracting the month/year portion from each stored date for comparison. By Day 26, regex had stopped feeling foreign and started feeling useful.


Day 27 — OOP: Rewriting the Finance Tracker with a Class

The final day of Week 4 — and of the month — was about Object-Oriented Programming. The task: take finance.py and reorganise it into a Finance class.

Same functionality. Different structure. Here's what changed:

import csv
import json
import os
import re
import sys

class Finance:
    @classmethod
    def add_transaction(cls):
        '''Adds the user transaction to a file as a dictionary'''
        while True:
            input_date = input("Enter the transaction date(dd/mm/yyyy): ").strip()
            if re.search(r"^\d{1,2}/ ?\d{1,2}/ ?\d{4}$", input_date):
                trans_date = input_date
                break
            else:
                print("Enter date in dd/mm/yyyy format!")
        while True:
            trans_type = input("Is it income or expense? ").strip().lower()
            if trans_type in ("income", "expense"):
                break

        trans_category = input("Enter the category you did the transaction for: ").strip().title()

        while True:
            try:
                trans_amount = float(input("Enter transaction amount: ").strip())
                break
            except ValueError:
                print("Enter the numbers!")

        while True:
            ask_user = input("Do you want to add a description[Y/N]? ").strip().upper()
            if ask_user in ("Y", "N"):
                break
        if ask_user == "Y":
            trans_descrp = input("Enter transaction description\n--> ")
        else:
            trans_descrp = None

        transaction = {"date": trans_date, "type": trans_type, "category": trans_category, "amount": trans_amount, "description": trans_descrp}
        with open("report.txt", "a") as report_file:
            report_file.write(f"{json.dumps(transaction)}\n")

    @classmethod
    def view_report(cls):
        '''Shows monthy income and monthly expense and net balance and returns the user input'''
        view_income = []
        view_expense = []
        total_income = 0
        total_expense = 0
        while True:
            view_month = input("Enter the month and year of the transaction(mm/yyyy): ").strip()
            if re.search(r"^\d{1,2}/ ?\d{4}$", view_month):
                break
            else:
                print("Enter in the mm/yyyy format!")
        with open("report.txt") as view_file:
            lines = view_file.readlines()
            if not lines:
                print("No Transactions To View!")
            else:
                for trans_dict in lines:
                    view_dict = json.loads(trans_dict)
                    if view_month == re.search(r"^\d{1,2}/ ?(\d{1,2}/ ?\d{4})$", view_dict['date']).group(1):
                        if view_dict['type'] == "income":
                            view_income.append(f"\t{view_dict['category']}: {view_dict['amount']}\n")
                            total_income += view_dict['amount']
                        else:
                            view_expense.append(f"\t{view_dict['category']}: {view_dict['amount']}\n")
                            total_expense += view_dict['amount']

                        print(f"===REPORT FOR {view_month}===")
                        for income_trans in view_income:
                            print("Income:")
                            print(income_trans)
                        print(f"Total Income: ${total_income}")
                        for expense_trans in view_expense:
                            print("Expenses: ")
                            print(expense_trans)
                        print(f"Total Expenses: ${total_expense}\n")
                        print(f"Net Balance: ${total_income - total_expense}")
        return view_month, total_income, total_expense

    @classmethod
    def export_report(cls):
        '''Exports monthly report to csv'''
        trans_month, total_income, total_expense = Finance.view_report()
        safe_month = trans_month.replace("/", "_")
        if total_income == 0 and total_expense == 0:
            print("No Transactions to Export!")
        else:
            if os.path.isfile(f"Report_{safe_month}.csv"):
                print("Report already exported!")
            else:
                with open(f"Report_{safe_month}.csv", "a", newline = "") as export_file:
                    writer = csv.DictWriter(export_file, fieldnames = ["Type", "Category", "Description", "Amount"], lineterminator = "\n")
                    writer.writeheader()
                    with open("report.txt") as info_file:
                        for info_dict in info_file.readlines():
                            new_dict = json.loads(info_dict)
                            if trans_month == re.search(r"^\d{1,2}/ ?(\d{1,2}/ ?\d{4})$", new_dict['date']).group(1):
                                writer.writerow({'Type': new_dict['type'], 'Category': new_dict['category'], 'Description': new_dict['description'], 'Amount': new_dict['amount']})

                    total_writer = csv.writer(export_file, lineterminator = "\n")
                    total_writer.writerows([[None, None, "Total Income", total_income],
                                            [None, None, "Total Expense", total_expense],
                                            [None, None, "Net Balance", total_income - total_expense]])    

    @classmethod
    def delete_trans(cls):
        delete_cat = input("Enter category of the transaction you want to delete: ").strip()
        delete_date = input("Enter the date of the transaction you want to delete(dd/mm/yyyy)")
        remaining_trans = []
        if os.path.isfile("report.txt"):
            with open("report.txt") as del_file:
                trans_lines = del_file.readlines()
                for trans_line in trans_lines:
                    Dict = json.loads(trans_line)
                    if delete_cat not in Dict.values() and delete_date not in Dict.values():
                        remaining_trans.append(Dict)

            with open("report.txt", "W") as new_file:
                for data in remaining_trans:
                    new_file.write(f"{json.dumps(data)}\n")
        else:
            print("No transaction to delete try adding a transaction!")

    @classmethod
    def delete_report(cls):
        ask_report = input("Enter the name of the report you want to delete: ")
        if os.path.isfile(f"{ask_report}.csv"):
            os.remove(f"{ask_report}.csv")
        else:
            print("NO Report Found With The Given Name")

def main():
    '''Main function'''
    print("===Personal Finance Tracker===")
    print("What would youy like to do?")
    print("SELECT THE CORRESPONDING NUMBER FOR THE GIVEN OPREATION")
    user_finance = Finance()
    while True:
        while True:
            usr_response = input("1. Add Transaction\n2. View Monthly Report\n3. Export Report To CSV\n4.Delete Transaction\n5.Delete Report\n6.Exit\n--> ").strip()
            if usr_response in ("1", "2", "3", "4", "5", "6"):
                break
        match usr_response:
            case "1":
                Finance.add_transaction()
            case "2":
                Finance.view_report()
            case "3":
                Finance.export_report()
            case "4":
                Finance.delete_trans()
            case "5":
                Finance.delete_report()
            case "6":
                sys.exit()


if __name__ == "__main__":
    main()

Everything is now a method inside the Finance class. Calling Finance.add_transaction() instead of just add_transaction() is a small syntax change with a big conceptual difference — the behaviour belongs to the class. It's the first step toward proper OOP thinking.

@classmethod means the method is called on the class itself rather than on an instance. This is my introduction to that concept and I know there's more — __init__, instance variables, inheritance — that I haven't touched yet. But having a class that groups related behaviour together already makes the code feel more organised.


📁 What I Built This Week

Project File Concepts Used
Note-Taking App notes.py File I/O, open(), os.remove(), if __name__
Expense Tracker expenses.py csv, DictWriter, DictReader, delete-and-rewrite
Email Validator validator.py + robust_validator.py re.fullmatch(), email-validator library
Log Parser log_parser.py re.findall(), capture groups, complex patterns
Personal Finance Tracker finance.py JSON persistence, CSV export, regex validation, full CRUD
Finance Tracker (OOP) finance_cls.py class, @classmethod, OOP refactoring

All the code is on GitHub — every week, every file:
👉 github.com/Omk4314/progress-on-python


What Actually Clicked This Week

  • File I/O is what makes programs real. The moment notes survive after the terminal closes, it stops being a script and starts being software.
  • JSON + files = a lightweight database. No setup, no dependencies — just structured data written line by line and read back perfectly.
  • Regex is a language inside a language. Intimidating at first, genuinely powerful once it clicks. The log parser going from raw text to clean IP + timestamp pairs in eight lines is still satisfying.
  • OOP is about grouping, not just syntax. Wrapping functions into a class didn't change what the code does — it changed how it's organised. That distinction matters.
  • if __name__ == "__main__": is a habit worth building early. Every project file has it now.

What I Want to Learn Next

Month 2 is going to go further:

  • OOP properly__init__, instance variables, inheritance, __str__
  • APIs — pulling real live data into Python
  • Virtual environments and pip — managing dependencies like a real project
  • Testingpytest, writing tests for my own code
  • A bigger project — something multi-file, with real users and real data

One month done. See you in Month 2. 🐍


Week 4 complete. Month 1 complete. The programs are real now.