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.
| 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.
See how Python reads a file and processes it line by line: Open in Python Tutor
The simplest way:
contents = open("data.txt").read()
print(contents)The better way (automatically closes the file when done):
with open("data.txt") as f:
contents = f.read()
print(contents)with open("data.txt") as f:
for line in f:
line = line.strip() # Remove the newline character
print(line)with open("output.txt", "w") as f:
f.write("Hello, world!\n")
f.write("Second line.\n")"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)
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
- 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."
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.
File not found:
open("data.txt") # FileNotFoundError if data.txt is not in your current folderFix: 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- 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 → |
|---|