File handling
Advancedwith 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.
- 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).
文體小知識:編程教學課每個概念都配一段可以親手試的代碼例子,照住輸入、改一改,最快學會。
§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
Letting a program read and write files so data survives after the program ends.
The function that opens a file, given a filename and a mode, e.g. open("a.txt", "r").
"r" reads only; "w" writes and wipes existing content; "a" appends at the end without destroying old data.
Closes the file automatically when the with block ends — the recommended file pattern.
read() returns the whole content as one string; readlines() returns a list of lines.
The special character meaning 'new line'; add it yourself in write(), strip it off lines you read.
A plain-text data format with comma-separated fields, one record per line, openable in Excel.
Splits a string at commas into a list, e.g. "Mary,85".split(",") gives ["Mary", "85"].
Putting risky code in try and handling named exceptions in except so the program keeps running.
3Step by step Steps
- 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.
- 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.
- 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.
- 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.
- "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.
- 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.
- 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
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.
- Read the file: with open("scores.txt") as f: line = f.read(), giving the string "85,90,78".
- Split the fields: parts = line.strip().split(","), giving ["85", "90", "78"] — strip first to remove any newline.
- Convert to numbers: scores = [int(p) for p in parts], giving [85, 90, 78] — a list of strings becomes a list of numbers.
- Average: average = sum(scores) / len(scores) = 253 / 3 ≈ 84.33.
- Answer: The three scores are 85, 90 and 78; the average is about 84.33.
6Common mistakes Mistakes
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.