DS 1501 · Lesson 22 of 24
Instructor: Corey Schafer24m
Sign in to watchPersist and inspect datasets stored on disk safely using Python file objects, modes, and context managers. What you will learn: • File paths, encoding='utf-8', and opening modes: 'r' (read), 'w' (write/truncate), 'a' (append), 'x' (exclusive create). • Why context managers ('with open(path, mode) as f:') guarantee automatic cleanup even if an error occurs. • Reading strategies: f.read() (entire string), f.readline() (single line), f.readlines() (list of lines), and memory-safe iteration 'for line in f:'. • Handling trailing newlines ('\n') cleanly with line.rstrip('\n') and writing lines with f.write(). University Outline Mapping: Class 22 · CO4 · Reading: 9.2–9.4 (deitel) · Activities: Lecture, Slides, Demonstration.
Note
Outline: Class 22 | CO4 | Reading: Deitel 9.2–9.4 Safe Line-by-Line Read Pattern: with open("scores.txt", "r", encoding="utf-8") as f: for line in f: clean = line.strip() Warning: Opening an existing file in mode 'w' ERASES all previous contents immediately — use 'a' to append!
Same resources as in the community course — sign in to watch the lesson and track progress.
Watch the whole course.
Sign in to play every lesson, track your progress, and ask questions alongside the community.
Already signed in? Open lesson in Community