CodeBlanks Logo Icon CodeBlanks

Summary - File I/O

Combine with, read and write to write a notes app.

Summary - File I/O

In this group you learned file opening, reading, writing, the with statement and modes. open returns a file object; encoding="utf-8" keeps Turkish text safe. read returns all content, readline one line, readlines a list of lines.

For writing, write writes one string and writelines a list of strings. The with block closes the file automatically at exit; that's why it's always preferred. Modes: r, w, a, x; add b for binary.

Mini task: keep a diary

As a summary you'll write a small diary app. With w mode you open the file and write the first line; with a mode you append the second line; with r mode you read the whole content as one string and print it.

You use three separate with blocks. The output has two lines; the \n markers stay in the file. This task shows how the modes work together.

Practice Three-mode diary

Write three with blocks. First with open("diary.txt", "w", encoding="utf-8") as f: f.write("Monday\n"). Second with open("diary.txt", "a", encoding="utf-8") as f: f.write("Tuesday\n"). Third with open("diary.txt", "r", encoding="utf-8") as f: print(f.read(), end=""). The output has two lines; pass end="" to print to avoid an extra line.

Starter code

main.py
# w mode: write Monday
# a mode: append Tuesday
# r mode: print all content (end="")

Sample solution

main.py
# w mode: write Monday
with open("diary.txt", "w", encoding="utf-8") as f:
    f.write("Monday\n")
# a mode: append Tuesday
with open("diary.txt", "a", encoding="utf-8") as f:
    f.write("Tuesday\n")
# r mode: print all content (end="")
with open("diary.txt", "r", encoding="utf-8") as f:
    print(f.read(), end="")

Expected output

Monday
Tuesday

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the best practice in file operations?

  • Skip the close call
  • Always prefer binary mode
  • Use the with statement Correct answer
  • Skip the encoding parameter

Explanation: The with statement provides automatic closing; that's the best practice.

2 Complete the with statement

Question
____ open("f.txt", "w", encoding="utf-8") as f:
    f.write("Hello")
Answer
with open("f.txt", "w", encoding="utf-8") as f:
    f.write("Hello")

Explanation: The with statement closes the file automatically.

3 Match the file operations

Term Meaning
open Opens a file
with Closes automatically
read Reads content
write Writes content

All lessons in Intermediate