Lesson 19 of 55
PythonFile I/O
20 minutes
Course progress35%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 19 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
Reading from and writing to files is straightforward with Python’s built‑in open() function, especially when used inside a with context manager.
# Write to a file
with open('example.txt', 'w') as f:
f.write('First line
Second line')
# Read the whole file
with open('example.txt', 'r') as f:
content = f.read()
print(content)
The with block guarantees that the file is properly closed, even if an error occurs inside the block.