Python
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.
Exercise 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.
Show example solution
# 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="")
Test yourself
-
What is the best practice in file operations?
- Skip the close call
- Always prefer binary mode
- Use the with statement
- Skip the encoding parameter
Show answer
Use the with statement — The with statement provides automatic closing; that's the best practice.
-
Complete the with statement
____ open("f.txt", "w", encoding="utf-8") as f:
f.write("Hello")
Show answer
with open("f.txt", "w", encoding="utf-8") as f:
f.write("Hello")
-
Match the file operations
- open
- Opens a file
- with
- Closes automatically
- read
- Reads content
- write
- Writes content
Next lesson: csv.reader