Read content only
Will error if file not found
Default mode
Erases old content!
Can write new data
Useful for fresh output
Preserves old content
Good for logs
Never erases
Can read and modify
Doesn't erase
Advanced use
Foundation lesson for file operations in Python. Learn to open files, read data, write data, and close files properly.
open() borrows the file. read/write. close() (or with) gives it back.
with open(...) as f: closes even if something goes wrong.
A file is data stored on disk that survives after your program ends. Unlike variables which disappear, files stay on your computer. Python can read from files (input) and write to files (output).
Files are used to store logs, save game progress, read configuration, store user data, analyze large text documents, process CSV data, and persist any information that needs to last beyond program execution.
"r" — read (default). File must exist."w" — write. Creates file or erases existing content."a" — append. Adds to end of file."r+" — read and write without erasing.file = open("name.txt", "r")file.close() or use withYour school stores grades in a text file: one line per student "Alice: 95". Your program reads the file line-by-line, processes the data, and writes results to a new file. Without files, all data is lost when the program ends.
readlines() for list of lines, or readline() for one line at a time.\n for newlines: file.write("Line 1\n")close().
Answer all questions, then click Check answers. Use this before Practice in the editor.
Q1. Safest everyday pattern to open files?
Q2. Mode 'r' means…
Q3. Mode 'a' is for…
Q4. Why close files?