Chapter 7

File Handling

Learn how to read from and write to files - making your programs work with real data!

📁 Why File Handling?

File handling lets your programs store and retrieve data permanently. Without files, your data disappears when the program ends. With files, you can save settings, store user data, process documents, and much more!

What Can You Do with Files?

📖 Read Data

Load configuration files, read user data, process documents

💾 Save Data

Store user preferences, save game progress, create logs

📊 Process Files

Analyze CSV data, parse JSON, process text files

📝 Generate Files

Create reports, export data, generate documents

Real-World Examples

Where File Handling is Used

Examples of file handling in real applications:

1. Configuration Files
   - Storing app settings (config.json, settings.ini)
   - User preferences and customization

2. Data Storage
   - Saving user accounts and profiles
   - Game save files
   - Application state

3. Logs and Monitoring
   - Error logs (error.log)
   - Access logs (access.log)
   - Debug information

4. Data Processing
   - Reading CSV files (sales_data.csv)
   - Processing JSON APIs
   - Analyzing text documents

5. File Generation
   - Creating reports (monthly_report.pdf)
   - Exporting data (export.xlsx)
   - Generating HTML pages

🔍 How File Operations Work

When your program works with files, here's what happens:

  1. Open: Python asks the operating system to access the file
  2. OS Check: Operating system checks permissions and locates the file
  3. File Descriptor: OS gives Python a "handle" to access the file
  4. Buffering: Data is temporarily stored in memory for efficiency
  5. Read/Write: Your program reads or writes through the buffer
  6. Close: Buffer is flushed, file handle is released

Important: Always close files when you're done! Unclosed files can cause data loss and resource leaks.

🔓 Opening and Closing Files

Before you can read or write a file, you must open it. When you're done, you must close it!

Basic File Operations

The Basic Pattern

Output will appear here...

⚠️ Important: The Problem with Manual Close

# What if an error happens?
file = open("data.txt", "r")
content = file.read()
# ... some code that might raise an error ...
file.close()  # This might NEVER execute if there's an error!

# Better approach (we'll learn this next!):
with open("data.txt", "r") as file:
    content = file.read()
# File automatically closes, even if there's an error!

File Paths - Where is Your File?

Output will appear here...

📂 Understanding File Paths

Path Type Example Meaning
Absolute (Windows) C:\\Users\\name\\file.txt Full path from drive letter
Absolute (Mac/Linux) /home/user/file.txt Full path from root /
Relative (current) file.txt File in current directory
Relative (subfolder) data/file.txt File in data subfolder
Relative (parent) ../file.txt File in parent directory

📖 Reading Files

There are several ways to read file content, each useful for different situations!

Method 1: read() - Read Entire File

Output will appear here...

💡 When to use read()

Good for: Small files, when you need all content at once

Bad for: Very large files (loads everything into memory!)

Method 2: readline() - Read One Line at a Time

Output will appear here...

Method 3: readlines() - Read All Lines as a List

Output will appear here...

Method 4: Iterating Over File Object (Best for Large Files!)

Output will appear here...

📊 Comparing Read Methods

Method Returns Use When
read() Entire file as string Small files, need all content
readline() One line as string Processing one line at a time
readlines() List of lines Need all lines in a list
for line in file Each line (iteration) Large files, memory efficient ⭐

✍️ Writing to Files

Writing to files lets you save data, create logs, generate reports, and more!

Basic Writing

Output will appear here...

writelines() - Write Multiple Lines

Output will appear here...

print() to Files - The Easy Way!

🔧 File Modes - How to Open Files

The mode parameter tells Python how you want to use the file!

r

Read Mode

Read only. File must exist

open("file.txt", "r")
w

Write Mode

Write. Creates new or overwrites existing

open("file.txt", "w")
a

Append Mode

Append. Adds to end of file

open("file.txt", "a")
x

Exclusive Create

Create. Fails if file exists

open("file.txt", "x")

Understanding File Modes

Output will appear here...

📋 Complete File Modes Reference

Mode Description If File Doesn't Exist If File Exists
'r' Read only (default) Error Opens for reading
'w' Write only Creates new file ⚠️ Overwrites!
'a' Append only Creates new file Appends to end
'x' Exclusive create Creates new file Error!
'r+' Read and write Error Opens for read/write
'w+' Write and read Creates new file ⚠️ Overwrites!
'a+' Append and read Creates new file Appends to end

💡 Text vs Binary Mode:

  • 't' - Text mode (default): 'r' = 'rt'
  • 'b' - Binary mode: 'rb', 'wb' for images, audio, etc.

🔐 The 'with' Statement - Automatic Cleanup!

The 'with' statement is the Pythonic way to work with files! It automatically closes the file when you're done, even if an error occurs. This is called a context manager.

Why Use 'with'?

The Old Way vs The Better Way

Output will appear here...

🔍 How 'with' Works

The 'with' statement uses special methods called __enter__ and __exit__:

with open("file.txt", "w") as file:
    file.write("Hello")

# Equivalent to:
file = open("file.txt", "w")
try:
    # __enter__ method is called
    file.write("Hello")
finally:
    # __exit__ method is called (closes file)
    file.close()

# Benefits:
# 1. Automatic cleanup
# 2. Cleaner code
# 3. Exception safe
# 4. No forgetting to close!

💡 Always Use 'with' for Files!

  • Automatic closing: No need to remember file.close()
  • Exception safe: File closes even if errors occur
  • Cleaner code: Less boilerplate, more readable
  • Resource management: Prevents resource leaks

Rule of thumb: If you're not using 'with', you're probably doing it wrong!

📊 Working with CSV Files

CSV (Comma-Separated Values) is a common format for storing tabular data. Think of it like a simple spreadsheet where values are separated by commas!

Manual CSV Handling

Output will appear here...

Using the csv Module (Better Way!)

Output will appear here...

🔗 Working with JSON Files

JSON (JavaScript Object Notation) is a popular format for storing and exchanging data. It's similar to Python dictionaries and lists!

JSON Basics

Output will appear here...

🔄 Python ↔ JSON Type Mapping

Python JSON
dict object
list, tuple array
str string
int, float number
True true
False false
None null

💡 JSON Methods Quick Reference

# To File
json.dump(data, file)    # Write Python object to file
json.load(file)          # Read JSON from file to Python object

# To String
json.dumps(data)         # Convert Python object to JSON string
json.loads(json_string)  # Convert JSON string to Python object

# Common parameters:
indent=4      # Pretty print with indentation
sort_keys=True  # Sort dictionary keys
ensure_ascii=False  # Allow Unicode characters

📺 Video Resources

Watch these videos to reinforce your understanding of file handling:

Python File Handling

Corey Schafer

Comprehensive guide to reading and writing files in Python, including best practices.

Watch Video

Working with CSV and JSON

Tech With Tim

Learn how to work with CSV and JSON files for data processing.

Watch Video

Python Context Managers

Real Python

Deep dive into the 'with' statement and context managers.

Watch Video

🤖 AI Learning Prompts

Use these prompts with AI assistants to deepen your understanding:

Understanding File Basics

I'm learning about file handling in Python. Please help me understand:

1. What happens behind the scenes when I open, read, and close a file?
2. Why is it important to close files? What happens if I don't?
3. Explain the difference between text mode and binary mode
4. What's the difference between absolute and relative file paths?
5. Show me 5 common mistakes beginners make with files

Use simple explanations and examples!

Mastering File Operations

Help me master file reading and writing:

1. When should I use read() vs readline() vs readlines() vs iteration?
2. Show me 10 different examples of reading files
3. Explain the difference between write() and writelines()
4. How do I handle large files that don't fit in memory?
5. Give me practice exercises for each reading method

Include complete working examples!

Working with Data Files

I want to learn to work with CSV and JSON files:

1. Show me how to read and write CSV files step by step
2. Explain the csv module and DictReader/DictWriter
3. How do I work with JSON data in Python?
4. When should I use CSV vs JSON?
5. Create a mini-project that reads CSV, processes it, and writes JSON

Make it practical with real-world examples!

💡 Tips for Using These Prompts:

  • Practice with real files: Create actual files and work with them
  • Handle errors: Ask about try-except with files
  • Build projects: Request file-based mini-projects
  • Learn pathlib: Ask about the modern pathlib module

✏️ Practice Exercises

File Safety Reminder:

⚠️ Be careful when writing files! Mode 'w' overwrites existing files. Always use 'x' if you don't want to overwrite, or check if file exists first.

Part 1: Guided Exercises

Guided Exercise 1: Log File Creator

What You'll Learn: How to append to files and create logs.

Time: 15 minutes

Create a Simple Logging System

Output will appear here...

Guided Exercise 2: Student Grade Manager

What You'll Learn: Working with CSV files to store structured data.

Time: 20 minutes

Create a Grade Management System

Output will appear here...

Part 2: Independent Practice

Challenge 1: To-Do List Manager

Difficulty: Medium | Time: 25 minutes

Task: Create a to-do list program that:

  • Saves tasks to a file (one task per line)
  • Can add new tasks
  • Can display all tasks
  • Can mark tasks as complete (delete from file)
Output will appear here...

🎉 Congratulations!

You've completed Chapter 7 and the entire Python basics course! You now know:

  • How to read and write files
  • Different file modes and when to use them
  • The importance of using 'with' statement
  • How to work with CSV and JSON files
  • File path handling

You're now ready to build real Python applications! Keep practicing and building projects to solidify your skills.

🎯 Knowledge Check

Test your understanding of file handling concepts!

Question 1: What is the main advantage of using the with statement when working with files?

Question 2: Which file mode should you use to add content to the end of an existing file without deleting its current contents?

Question 3: What is the difference between read() and readlines()?

Question 4: When working with CSV files in Python, what module should you import?

Question 5: What does json.loads() do?

🎓 Congratulations on Completing This Chapter!

You've mastered file handling - a critical skill for real-world Python programming! You can now read data from files, write results to files, and work with common data formats like CSV and JSON. This opens up endless possibilities for creating practical applications!