Create a simple text file "notes.txt" with a few lines. Write a script to read and print its contents. (Concepts: opening files, read(), close())
# Assume notes.txt exists with lines like "Line 1\nLine 2\nLine 3"
file = open("notes.txt", "r") # r for read
content = file.read()
file.close()
print("File contents:\n", content)Explanation Notes (Like Me Explaining to Students): Students, Day 20: Interact with files—persistent data! open("notes.txt", "r")—opens for reading ("r" mode). file.read() loads all as string into content. file.close() frees resources (important!). Print it.
Run: If file has "Hello\nWorld", prints with newlines. Create the file first (use a text editor). In time, try readline() for one line or "w" mode to write. Files store beyond runtime—key for apps. Handles real data!
Key Concepts:
- Opening Files (open()): Function to access files; modes like "r" (read), "w" (write).
- .read(): File method that returns the entire contents as a string.
- .close(): Closes the file handle to free system resources.
