📁 Chapter 7: Files - Teaching Your Computer to Read and Write

Test your understanding of file handling in Python!

📂 File Basics

1. Why is working with files important in Python?

  • Files make programs run faster
  • Files allow programs to store and retrieve real business data
  • Files are required for all Python programs
  • Files automatically fix programming errors
Correct! Files allow your programs to work with real business data like customer lists, sales records, and reports - making your automation truly useful.

2. What function do you use to open a file in Python?

  • file()
  • open()
  • read()
  • load()
Correct! The open() function is like asking for the key to a specific room - you tell Python which file you want to access.

3. Where should you put your .txt files to avoid "FileNotFoundError"?

  • Anywhere on your computer
  • In the same folder as your Python script
  • In a special Python folder
  • On your desktop
Correct! Keep your .txt files in the same folder as your Python script - like keeping your coffee mug next to your coffee maker!
🔑 File Modes - The Three Keys

4. What does the 'r' mode do when opening a file?

  • Removes the file
  • Reads the file (like browsing a catalog)
  • Renames the file
  • Replaces the file
Correct! The 'r' mode means "read" - you're just looking at what's inside the file, like browsing a catalog.

5. What happens when you open a file with 'w' mode?

  • It adds to the end of the file
  • It creates a new file and erases any existing content
  • It only reads the file
  • It makes the file write-protected
Correct! The 'w' mode is like using a fresh piece of paper - it erases what was there before and starts new.

6. What does 'a' mode do?

  • Allows reading only
  • Automatically saves the file
  • Appends new content to the end of the file
  • Activates the file
Correct! The 'a' mode appends content to the end of the file, like adding a new entry to your diary.
🤝 The Magic of 'with open()'

7. Why is "with open(...) as f:" better than just using "open()"?

  • It's faster
  • It automatically closes the file when done
  • It uses less memory
  • It prevents file corruption
Correct! "with open()" is like having a responsible friend who always locks the door behind you - it ensures the file is properly closed.

8. What does the "as f:" part do in "with open('file.txt', 'r') as f:"?

  • It creates a variable 'f' to represent the file
  • It formats the file
  • It filters the file content
  • It makes the file faster
Correct! The "as f:" creates a variable 'f' that represents the opened file, so you can use f.read(), f.write(), etc.
📖 Reading Files

9. What does .read() do?

  • Reads only the first line
  • Reads the entire file content at once
  • Reads one character at a time
  • Reads only numbers from the file
Correct! .read() reads the entire file content at once, like reading a whole letter from start to finish.

10. What does .strip() do when reading file lines?

  • Removes the file
  • Removes invisible characters like extra spaces and newlines
  • Makes text lowercase
  • Counts the characters
Correct! .strip() is like a digital lint roller - it removes invisible characters from the start and end of text.

11. How do you read a file line by line?

  • Use a for loop: for line in f:
  • Use while True:
  • Use .read() multiple times
  • Use .split() function
Correct! You can use "for line in f:" to read each line one at a time, which is perfect for processing lists of names or data.
✍️ Writing Files

12. What method do you use to write text to a file?

  • f.print()
  • f.write()
  • f.add()
  • f.insert()
Correct! f.write() is used to write text to a file, like dictating a letter to an assistant.

13. What's the difference between writing ('w') and appending ('a') to a file?

  • Writing is faster than appending
  • Writing erases existing content, appending adds to the end
  • There's no difference
  • Appending is only for numbers
Correct! Writing ('w') starts fresh and erases what was there before, while appending ('a') adds to the end like adding to a diary.
🔍 Code Analysis

14. What will this code do?

with open('clients.txt', 'r') as f: content = f.read() print(content)
  • Create a new file called clients.txt
  • Read and display the entire contents of clients.txt
  • Delete the clients.txt file
  • Count the lines in clients.txt
Correct! This code opens clients.txt in read mode, reads all the content, and displays it on screen.

15. What's wrong with this code?

with open('nonexistent.txt', 'r') as f: content = f.read() print(content)
  • Missing parentheses
  • It will cause FileNotFoundError if the file doesn't exist
  • Wrong file mode
  • Nothing is wrong
Correct! If 'nonexistent.txt' doesn't exist, Python will raise a FileNotFoundError when trying to read it.

16. What will this code create?

with open('sales_report.txt', 'w') as f: f.write("Daily Sales Report\n") f.write("Total Sales: $1,250.00\n") f.write("New Customers: 3\n")
  • A Python script
  • A text file with a sales report
  • A spreadsheet
  • A database
Correct! This code creates a text file called 'sales_report.txt' with three lines of sales information.
✏️ Fill in the Blanks

17. Complete this file reading code:

open('inventory.txt', '') as f: for line in f: product = line.() print(f"Checking stock for: {product}")

Fill in: The keyword to safely open files, the mode to read files, and the method to clean up line endings.

Correct answers: "with", "r", "strip" - This safely opens a file for reading and cleans up each line.
✅ True or False

18. You must always close files manually when using "with open()".

  • True
  • False
Correct! False! The "with open()" statement automatically closes the file when done, even if an error occurs.

19. File names are case-sensitive in Python.

  • True
  • False
Correct! True! Python is very literal about file names - 'clients.txt' and 'Clients.txt' are different files.

20. You can use f-strings when writing to files.

  • True
  • False
Correct! True! You can use f-strings with f.write() to create dynamic content like f.write(f"Hello {name}!").
🌍 Real-World Application

21. What would be the best approach for keeping a running log of customer support events?

  • Use 'w' mode to start fresh each time
  • Use 'a' mode to append new entries
  • Use 'r' mode to read existing entries
  • Create a new file each time
Correct! Use 'a' mode to append new entries to the end of the log file, like adding pages to a diary.

22. For processing a client list for mass email, which approach is most efficient?

  • Read the entire file with .read() and process it
  • Use a for loop to read one line at a time
  • Open and close the file multiple times
  • Copy the file content manually
Correct! Using a for loop to read one line at a time is memory-efficient and perfect for processing lists of names or data.

🎉 Quiz Complete!

Your Score: 0/22

Keep practicing!