Skip to content
dreamcode
dreamcode
Map
File handling
Lesson 41 of 77
+15 XP on finish
PYTHON INTERMEDIATEChapter 7 · Errors, Files and Modules

File handling

Use the with statement and open() function to open files. The context manager automatically closes the file when the block ends.

Worked example

How it reads

  • open("sky.txt", "w") opens a file named sky.txt for writing
  • with ... as f automatically closes the file object
Cloud tip: Always prefer with open(...) to manual file opening to prevent memory leaks.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Before reading the file back, open it again in append mode ("a") and add a third line third entry. All three lines should print.

Press Run to check your work.