Quiz 2

File Operations — Reading & Writing

759 words
4 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# File Operations — Reading & Writing > **Why read this?** Variables hold data only while the program runs. To save data permanently (user settings, logs, documents), you need files.

File Operations — Reading & Writing

Why read this? Variables hold data only while the program runs. To save data permanently (user settings, logs, documents), you need files. File I/O lets your programs read from and write to the disk — making data persistent across runs.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Open files with open() in different modes
  2. Read files: read(), readline(), readlines()
  3. Write files: write(), writelines()
  4. Use with statement for safe file handling
  5. Understand file modes: r, w, a, r+, b

📋 Prerequisites

  • Basic understanding of strings and loops.
  • This topic is standalone — no advanced prerequisites.

📖 Core Content

25.1 What Problem Do File Operations Solve?

Intuition: Every time you open a document in Microsoft Word, your computer reads a file from disk. When you save, it writes to disk. File I/O is how programs communicate with persistent storage — data that stays even after the program ends.

25.2 Opening and Closing Files

python
# runnable
# BAD way (forgetting to close)
f = open("example.txt", "r")
content = f.read()
f.close()  # easy to forget!
# GOOD way (auto-closes)
with open("example.txt", "r") as f:
    content = f.read()
# File is automatically closed here
Always use with open(...) as f: — it automatically closes the file, even if an error occurs.

25.3 File Modes

ModeMeaningCreates File?Position
"r"Read (text)NoStart
"w"Write (text)Yes (overwrites)Start
"a"Append (text)Yes (if missing)End
"r+"Read + WriteNoStart
"rb"Read (binary)NoStart
"wb"Write (binary)YesStart

25.4 Reading Files

python
# runnable
# Assume example.txt contains:
# Line 1
# Line 2
# Line 3
with open("example.txt", "r") as f:
    # Read entire file
    content = f.read()
    print("All content:")
    print(content)
with open("example.txt", "r") as f:
    # Read line by line
    for line in f:
        print(f"Line: {line.strip()}")
with open("example.txt", "r") as f:
    # Read all lines into list
    lines = f.readlines()
    print(f"Lines: {lines}")

25.5 Writing Files

python
# runnable
with open("output.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("This is line 2.\n")
    f.write("And line 3.\n")
with open("output.txt", "r") as f:
    print(f.read())
# Appending
with open("output.txt", "a") as f:
    f.write("This line is appended.\n")
with open("output.txt", "r") as f:
    print(f.read())

25.6 Worked Example 1: Copy a File

python
# runnable
source = "example.txt"
dest = "copy.txt"
with open(source, "r") as src, open(dest, "w") as dst:
    for line in src:
        dst.write(line)
print(f"Copied {source} to {dest}")

25.7 Worked Example 2: Write User Data to CSV

python
# runnable
with open("users.csv", "w") as f:
    f.write("name,age,city\n")
    f.write("Alice,25,New York\n")
    f.write("Bob,30,Los Angeles\n")
    f.write("Charlie,22,Chicago\n")
with open("users.csv", "r") as f:
    for line in f:
        print(line.strip())

25.8 Worked Example 3: Read and Process Numbers

python
# runnable
# Write numbers first
with open("numbers.txt", "w") as f:
    for i in range(1, 11):
        f.write(f"{i}\n")
# Read and sum them
total = 0
with open("numbers.txt", "r") as f:
    for line in f:
        total += int(line.strip())
print(f"Sum: {total}")  # 55

⚠️ Common Pitfalls

Pitfall 1: Forgetting to Close Files

The mistake: f = open("file.txt"); content = f.read() and never calling f.close(). Risk: Resource leak — the file stays open until the program ends. Fix: Always use with open(...) as f:.

Pitfall 2: Writing Mode Overwrites

The mistake: Using "w" mode when you meant to append. The file is erased first. Fix: Use "a" (append) mode if you want to add to existing content.

Pitfall 3: File Not Found

The mistake: open("nonexistent.txt", "r") Error: FileNotFoundError: [Errno 2] No such file or directory Fix: Check if file exists (import os; os.path.exists(path)) or use try/except.

Pitfall 4: Reading Without Stripping Newlines

The mistake: for line in f: print(line) prints an extra blank line because each line already ends with \n. Fix: Use line.strip() or line.rstrip('\n').

📝 Practice Questions

Q1: What does "w" mode do if the file already exists?
Answer: It overwrites (truncates) the file. All existing content is lost! Q2: Write code to count the number of lines in a file.
Answer:
python
with open("file.txt", "r") as f:
    count = sum(1 for line in f)
print(f"Lines: {count}")
Q3-10: Additional file operation questions.
(Following pattern.)

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.