Thread Closed 
Thread Rating:
CHAPTER 16 — File Handling: Reading & Writing Data
#1
Chapter 16 — File Handling: Reading & Writing Data
This chapter teaches how Python reads and saves real files — unlocking data storage, logs, documents, and real applications.

Programs become powerful when they interact with files:

• save notes 
• keep scores 
• store settings 
• load data 
• create logs 
• write reports 

Python makes this simple using the built-in open() function.

---

16.1 Opening a File

Format:
Code:
open(filename, mode)

Common modes:

Code:
"r"  read only
"w"  write (overwrites file)
"a"  append (add to end)
"r+" read & write

---

16.2 Reading a File

Example file: notes.txt

Code:
with open("notes.txt", "r") as file:
    content = file.read()
    print(content)

with automatically closes the file — very important.

---

16.3 Reading Line by Line

Code:
with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())

.strip() removes the newline at the end.

---

16.4 Writing to a File

"w" overwrites the file:

Code:
with open("output.txt", "w") as file:
    file.write("Hello from Python!\n")

If the file doesn't exist, Python creates it.

---

16.5 Appending to a File

"a" adds content without deleting what's already inside.

Code:
with open("log.txt", "a") as file:
    file.write("New entry added.\n")

---

16.6 Writing Multiple Lines

Code:
lines = ["First line\n", "Second line\n", "Third line\n"]

with open("multi.txt", "w") as f:
    f.writelines(lines)

---

16.7 Checking if a File Exists

Code:
import os

if os.path.exists("test.txt"):
    print("File found!")
else:
    print("Not found.")

---

16.8 Reading Data and Converting Types

Example file:


12 
27 

Reading as numbers:

Code:
numbers = []
with open("nums.txt", "r") as f:
    for line in f:
        numbers.append(int(line))

print(numbers)

---

16.9 Saving Structured Data (Simple Format)

Saving:

Code:
with open("profile.txt", "w") as f:
    f.write("name=Mia\n")
    f.write("age=14\n")

Reading:

Code:
profile = {}
with open("profile.txt", "r") as f:
    for line in f:
        key, value = line.strip().split("=")
        profile[key] = value

Now:
Code:
profile["name"]
profile["age"]

---

16.10 Using JSON for Data Storage

Perfect for storing dictionaries.

Code:
import json

data = {"name": "Lee", "score": 95}

with open("save.json", "w") as f:
    json.dump(data, f)

Loading:

Code:
with open("save.json", "r") as f:
    loaded = json.load(f)

print(loaded)

---

16.11 Mini Project — Simple Notes App

Write a program:

1. Ask the user to type a note 
2. Append it to notes.txt 
3. Confirm “Note saved.” 

Each new note goes on a new line.

---

16.12 Challenge — High Score System

Requirements:

• File: highscores.txt 
• Ask for a player name and score 
• Save them in the format: 
 
Code:
Mia: 42
 
• After saving, load the whole file 
• Display all scores sorted by score 

BONUS: 
Find the highest scorer and display their name.

---

16.13 Chapter Summary

• open() controls reading/writing 
• "w" overwrites, "a" appends 
• use with open(...) to avoid errors 
• .read(), .readline(), loops for reading 
• JSON is excellent for structured data 
• file handling allows real persistent programs 

Next:
Chapter 17 — Errors & Exception Handling

This is where beginners learn how to make programs crash-proof, safe, and professional.

---

Written and Compiled by Lee Johnston — Founder of The Lumin Archive
« Next Oldest | Next Newest »
Thread Closed 


Forum Jump:


Users browsing this thread: 1 Guest(s)