📁 Day 6: File Operations

Reading and Writing Files

📚 What You'll Learn Today

File operations let your programs read and write data to disk:

📂 Opening Files

Use the open() function to work with files:

Basic Syntax:

file = open("filename.txt", "r") # "r" = read mode # Do something with file file.close()

File Modes:

Mode Description
"r" Read (default)
"w" Write (overwrites)
"a" Append (add to end)
"r+" Read and write

📖 Reading Files

Read Entire File:

file = open("myfile.txt", "r") content = file.read() print(content) file.close()

Read Line by Line:

file = open("myfile.txt", "r") for line in file: print(line.strip()) # strip() removes newlines file.close()

Read into List:

file = open("myfile.txt", "r") lines = file.readlines() print(lines) # List of lines file.close()

✍️ Writing Files

Write (overwrites):

file = open("output.txt", "w") file.write("Hello, World!\n") file.write("This is line 2.\n") file.close()

Append (add to end):

file = open("output.txt", "a") file.write("This is added later.\n") file.close()

✅ The "with" Statement

Always use with - it automatically closes the file even if errors occur:

# BEST PRACTICE - Always use this! with open("myfile.txt", "r") as file: content = file.read() print(content) # File automatically closed here!
💡 Why use "with"? If your code has an error before calling close(), the file might not be saved properly. The "with" statement guarantees the file is closed.

📊 Working with CSV

CSV (Comma-Separated Values) is great for data:

Reading CSV:

import csv with open("data.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row)

Writing CSV:

import csv data = [ ["Name", "Age", "City"], ["Alex", "25", "NYC"], ["Jordan", "30", "LA"] ] with open("output.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerows(data)

🏋️ Exercise: Todo List App

Create a simple todo list that saves to a file!

# 1. Read existing todos from file # 2. Add a new todo # 3. Save back to file # 4. Display all todos

Example Solution:

FILE_NAME = "todos.txt" def read_todos(): try: with open(FILE_NAME, "r") as f: return [line.strip() for line in f] except FileNotFoundError: return [] def add_todo(todo): with open(FILE_NAME, "a") as f: f.write(todo + "\n") # Test it add_todo("Learn Python") add_todo("Build a project") print(read_todos())

✅ Key Takeaways

🎉 Ready for the Final Day?

Tomorrow is Day 7 - you'll build a complete calculator project!

Marking complete will unlock Day 7!