Files and Paths¶
Try This First: Before reading, try this in Python:
open('test.txt', 'w').write('hello')thenprint(open('test.txt').read()). You just wrote to a file and read it back.
Learn Your Way¶
| Read | Build | Watch | Test | Review | Visualize |
|---|---|---|---|---|---|
| You are here | Projects | Videos | Quiz | Flashcards | Diagrams |
Programs read data from files and write results to files. Understanding how to work with files and their locations (paths) is essential.
Visualize It¶
See how Python reads a file and processes it line by line: Open in Python Tutor
Reading a file¶
The simplest way:
The better way (automatically closes the file when done):
Reading line by line¶
with open("data.txt") as f:
for line in f:
line = line.strip() # Remove the newline character
print(line)
Writing to a file¶
"w"means write (creates new file or overwrites existing)"a"means append (adds to end of existing file)"r"means read (default, whatopen()uses without a mode)
What is a path?¶
A path is the address of a file on your computer:
- Windows: C:\Users\alice\projects\data.txt
- Mac/Linux: /Users/alice/projects/data.txt
Relative vs absolute paths¶
- Absolute: Full address from the root —
C:\Users\alice\projects\data.txt - Relative: Address from where you are now —
data.txtor../other_folder/file.txt
.. means "go up one folder." So ../data.txt means "go up one folder, then find data.txt."
Using pathlib (the modern way)¶
from pathlib import Path
# Create a path
data_file = Path("data/sample.txt")
# Check if it exists
if data_file.exists():
contents = data_file.read_text()
# Get parts of the path
data_file.name # "sample.txt"
data_file.stem # "sample"
data_file.suffix # ".txt"
data_file.parent # Path("data")
You will use pathlib starting in Level 0. For Level 00, plain open() is fine.
Common mistakes¶
File not found:
Fix: make sure you are in the right directory (cd to the project folder first).
Forgetting to strip newlines:
for line in open("data.txt"):
print(line) # Double-spaced output because each line has \n
# Fix: print(line.strip())
Using backslashes on Windows:
# Wrong (backslash is an escape character)
path = "C:\Users\alice\new_file.txt" # \n becomes a newline!
# Right
path = "C:\\Users\\alice\\new_file.txt" # Escaped backslashes
path = r"C:\Users\alice\new_file.txt" # Raw string (r prefix)
path = Path("C:/Users/alice/new_file.txt") # Forward slashes work too
Practice¶
- Level 00 / 14 Reading Files
- Level 0 / 01 Terminal Hello Lab
- Level 0 / 02 Calculator Basics
- Level 0 / 03 Temperature Converter
- Level 0 / 04 Yes No Questionnaire
- Level 0 / 05 Number Classifier
- Level 0 / 06 Word Counter Basic
- Level 0 / 07 First File Reader
- Level 0 / 08 String Cleaner Starter
- Level 0 / 09 Daily Checklist Writer
Quick check: Take the quiz
Review: Flashcard decks Practice reps: Coding challenges
| ← Prev | Home | Next → |
|---|---|---|