Python 3 Tutorial · Chapter 21 of 22
Python File Handling
Create, write, read, and update text files in the work folder.
open(name, mode) works with relative files such as student.txt inside the run folder.
Always close files (or use with). The sandbox blocks os/subprocess — keep paths relative.
File sample
Try it Yourself »
# CREATE + WRITE
with open("student.txt", "w", encoding="utf-8") as file:
file.write("Ana Santos\n")
file.write("BSCS\n")
print("Create/Write: student.txt saved.")
# READ
with open("student.txt", "r", encoding="utf-8") as file:
name = file.readline().strip()
course = file.readline().strip()
print(f"Read: {name} - {course}")
# UPDATE (rewrite file)
with open("student.txt", "w", encoding="utf-8") as file:
file.write("Ana Santos\n")
file.write("BSIT\n")
print("Update: course changed to BSIT.")
Classroom Tips
- Use relative names only (student.txt).
- os.remove is blocked in the sandbox — rewrite or clear instead.