File handling

Advanced

with open("file", "w") as f writes, "r" reads, "a" appends; read()/readlines()/for line handle lines; CSV fields split by split(","); try-except catches FileNotFoundError so the program never crashes.

For:Secondary 3 Information & Communication Technology · Unit:Programming II · Lesson 2 of 13 in the learning path

After this lesson, you can:
  • Variables vanish when a program ends; files keep data for good.
  • with open("file", "mode") as f is the standard pattern — it closes for you.
  • Three modes: "r" read, "w" write (wipes), "a" append (keeps).
文體:編程教學課有聲朗讀

文體小知識:編程教學課每個概念都配一段可以親手試的代碼例子,照住輸入、改一改,最快學會。

資訊及通訊科技Information & Communication Technology

§Text Passage

1When a program ends, everything in its variables disappears — to keep scores or records, write them into a file. Python opens files with open(): open("scores.txt", "w") opens for writing, "r" reads, "a" appends. The safest form is with open("scores.txt", "w") as f: — the file closes automatically when the block ends, so you never forget.

2Three ways to read: f.read() returns the whole content at once; f.readlines() gives a list of lines; or for line in f: handles one line at a time. Every line read carries a newline character \n at the end — line.strip() cleans it off. To write, f.write("Mary,85\n") — add the \n yourself, because write never adds one.

3CSV (Comma-Separated Values) is the most common data file format: one record per line, fields split by commas, such as "Mary,85,3A". line.split(",") breaks the line into ["Mary", "85", "3A"], and int("85") turns the text into the number 85 — Excel opens CSV files directly too.

4Real programs always meet surprises: a file may not exist (FileNotFoundError) or text may refuse to become a number (ValueError). Catching these with try-except keeps the program alive: try: open and read the file, except FileNotFoundError: print("file not found") — tell the user and carry on. That is what reliable software looks like.

1Summary 重點摘要

with open("file", "w") as f writes, "r" reads, "a" appends; read()/readlines()/for line handle lines; CSV fields split by split(","); try-except catches FileNotFoundError so the program never crashes.

2Vocabulary cards Vocabulary

F
File handling檔案處理

Letting a program read and write files so data survives after the program ends.

o
open()開檔函數

The function that opens a file, given a filename and a mode, e.g. open("a.txt", "r").

M
Mode "r" / "w" / "a"讀取/寫入/附加模式

"r" reads only; "w" writes and wipes existing content; "a" appends at the end without destroying old data.

w
with ... as f自動關檔語法

Closes the file automatically when the with block ends — the recommended file pattern.

r
read() / readlines()讀取方法

read() returns the whole content as one string; readlines() returns a list of lines.

N
Newline character \n換行符

The special character meaning 'new line'; add it yourself in write(), strip it off lines you read.

C
CSV逗號分隔值檔

A plain-text data format with comma-separated fields, one record per line, openable in Excel.

s
split(",")分割字串

Splits a string at commas into a list, e.g. "Mary,85".split(",") gives ["Mary", "85"].

t
try-except異常處理

Putting risky code in try and handling named exceptions in except so the program keeps running.

3Step by step Steps

  1. Write your first fileFor example: with open("hello.txt", "w") as f: f.write("Hello!\n"). After running, the folder gains hello.txt containing Hello! — mode "w" creates the file if it does not exist. Modes decide what happens after opening: "w" writes, "r" reads and "a" appends; after the run, open hello.txt in a text editor to confirm the write really worked.
  2. with closes for youFor example: with open("hello.txt", "w") as f: f.write("A") f.write("B") — Python calls close() automatically when the block ends; with f = open(...) you must remember f.close() yourself. A file never closed may not finish saving its data, so records can be lost; handing the closing over to with is the standard style for file handling.
  3. Read the whole fileFor example: hello.txt contains Hello!; with open("hello.txt") as f: print(f.read()) prints Hello! — no mode means the default "r". read() returns the whole file as one string, which suits small files; for large ones, reading line by line saves memory — a difference that matters with big data.
  4. Reading line by lineFor example: scores.txt has two lines, 85 and 90; for line in f: print(line.strip()) prints 85 then 90 — strip() removes the trailing \n, or print would jump an extra line. strip() only removes whitespace at both ends of the string, leaving the middle untouched; every line read in carries \n, so strip before processing is the routine.
  5. "w" wipes vs "a" appendsFor example: the old file holds ABC. Writing X with "w" leaves only X (old content wiped); writing X with "a" leaves ABCX (kept, then added). To preserve records, use "a". Opening with "w" wipes the old content at once, even if nothing is written; "a" moves to the end and appends after the old records. Log files almost always use "a", because history must not be overwritten.
  6. Handling one CSV lineFor example: a line reads "Mary,85,3A". parts = line.strip().split(",") gives ["Mary", "85", "3A"]; score = int(parts[1]) turns "85" into the number 85, ready for averaging. split(",") cuts the string at every comma and returns a list, and lists count from zero, so parts[1] is the second item; scores must pass through int() before you can compare or average them.
  7. Catching errors with try-exceptFor example: try: f = open("data.txt") except FileNotFoundError: print("file not found"). A missing data.txt prints the message instead of crashing; conversion slips like int("abc") are caught by except ValueError:. Several except blocks can be chained to catch different errors, and a final else runs only when nothing went wrong, making the messages clearer.

4Diagrams Diagrams

Python 檔案處理:開・讀・寫・關 File handlingf = open("notes.txt", "w") # w 寫入f.write("今日學會開檔!")f.close() # 用完要關"w" 寫入清空重寫"a" 附加加喺尾,唔刪舊"r" 讀取打開睇內容應用:程式關機後數據都唔見——寫入檔案先可以保存成績、日記、紀錄最佳實踐:用 with open(...) as f:——自動幫你關檔,唔怕漏
Fig. 1: File handling

5Worked example Example

Example: scores.txt holds one line "85,90,78". Write a program to read these three test scores and work out the average.

  1. Read the file: with open("scores.txt") as f: line = f.read(), giving the string "85,90,78".
  2. Split the fields: parts = line.strip().split(","), giving ["85", "90", "78"] — strip first to remove any newline.
  3. Convert to numbers: scores = [int(p) for p in parts], giving [85, 90, 78] — a list of strings becomes a list of numbers.
  4. Average: average = sum(scores) / len(scores) = 253 / 3 ≈ 84.33.
  5. Answer: The three scores are 85, 90 and 78; the average is about 84.33.

6Common mistakes Mistakes

✗ Leaving a file open after open() — no harm, right?
✓ Without closing, data may never reach the disk; with open(...) as f lets Python close it automatically.
✗ Opening an old file with "w" and expecting the old content to stay.
✓ "w" wipes the file the moment it opens; to keep old data and add at the end, use "a".
✗ Adding 5 straight onto "85" read from a file.
✓ Everything read is a string: "85" + 5 fails; convert with int("85") before any maths.
✗ Blaming a broken file when print(line) leaves blank lines.
✓ That is the newline \n at each line's end; line.strip() cleans it up.
✗ Accepting a crash when a file is missing as unavoidable.
✓ Catch FileNotFoundError with try-except, show a friendly message and keep the program running.

7Quick check Quick check

Q1Which open mode wipes the file's existing content? A. "r" B. "w" C. "a"

Q2What is the main benefit of with open("a.txt") as f:?

Q3What does "85,90".split(",") return?

Q4What happens with int("abc")?

Q5Which exception appears when open("data.txt") finds no file?

8Recap Recap

  • Variables vanish when a program ends; files keep data for good.
  • with open("file", "mode") as f is the standard pattern — it closes for you.
  • Three modes: "r" read, "w" write (wipes), "a" append (keeps).
  • Read three ways: read() all at once, readlines() as a list, for line one by one; strip() removes \n.
  • CSV: split(",") for fields, int() for numbers; try-except catches FileNotFoundError and ValueError.

Other subjects in this grade

Same subject, other grades