After understanding what files are, the first skill students must master is how to write text to a file and how to read text from a file. In Python, this is done through the open() function, which takes a file path, a mode, and an encoding, returning a file object for reading or writing. The safest and most recommended pattern is using with open(...) as f: because it automatically closes the file when the block finishes, even if an error occurs. This prevents data loss or locked files.
Example A: Create & Write
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("Learned Python file writing today.n")
f.write("This is the second line.n")
print("Write complete.")
When you run this, a file named notes.txt will appear in your working directory, containing the two lines of text. The mode "w" means “write”; if the file already exists, it will be overwritten, and if not, it will be created. The argument encoding="utf-8" ensures that Chinese and special characters appear correctly.
Next, we can read back the content of this file. The simplest method is read(), which reads the entire file as a string.
Example B: Read
with open("notes.txt", "r", encoding="utf-8") as f:
content = f.read()
print("File content:")
print(content)
Output example B:
File content:
Learned Python file writing today.
This is the second line.
If the file is long, or if you prefer to process it line by line, you can use a loop.
Example C: Loop
with open("notes.txt", "r", encoding="utf-8") as f:
for line in f:
print("LINE:", line.strip())
Output example C:
LINE: Learned Python file writing today.
LINE: This is the second line.
Line-by-line reading is memory-friendly and useful for large files or data processing.
At this point, students can try changing the filename or folder to see where the file is created. For example, with open("data/mylog.txt", "w", encoding="utf-8") will create a file inside a folder named data. This helps them understand relative and absolute paths.
If we don’t want to overwrite the file but instead append to the end, we use mode 'a'.
Example D: Append
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("This line was appended.n")
print("Append complete.")
Opening the file again will show the new line added after the previous content. This is perfect for logging or keeping a running history.
To combine writing and reading, consider a more interesting example — a mini diary program that records a short entry each time the program runs, adding the current date and time, then reads and displays the latest three entries.
Hands-on Practice: A mini diary
import time
entry = input("Write your diary entry: ").strip()
stamp = time.strftime("%Y-%m-%d %H:%M:%S")
with open("diary.txt", "a", encoding="utf-8") as f:
f.write(f"[{stamp}] {entry}n")
with open("diary.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
print("nRecent entries:")
for line in lines[-3:]:
print(line.strip())
Output example:
Write your diary entry: Completed the file reading lesson!
Recent entries:
[2025-10-11 14:30:01] Reviewed dictionary operations
[2025-10-11 15:05:12] Learned about file basics
[2025-10-11 15:40:27] Completed the file reading lesson!
The time.strftime() function generates a formatted date and time string. Using "a" ensures that each run appends to the same file rather than replacing it. readlines() loads all lines into a list, and lines[-3:] retrieves the last three entries for review. Through this small project, students experience how a program can remember information between runs — a core idea behind data persistence.
To conclude, first, open() requires three arguments: file path, mode, and encoding. Second, using with open(...) as f: is best practice to ensure files are closed properly. Third, 'w' overwrites files while 'a' appends new content. Mastering these rules prepares students to handle more advanced file formats like CSV and JSON safely and correctly.