Files and errors
Đã giới thiệu| English | Ý nghĩa |
|---|---|
| exception/ekˈsepʃn/ | ngoại lệ |
Why does the game crash for new players?
- A game reads the player's text size from
settings.txt. It works on the developer's computer. On a new player's first run there is no file yet, and the game stops withFileNotFoundError. - Programs meet a messy world: missing files, typing mistakes, bad data. This lesson shows how to read and write files, and how to plan for the errors you can expect.
Reading a file
with open("scores.txt") as f:opens the file and closes it for you when the block ends, even if an error happens inside.- Looping
for line in f:gives one line at a time, with its"\n"on the end. Callline.strip()before you split or convert it.
total = 0
with open("scores.txt") as f: # Ana,72 Ben,55 Cai,90
for line in f:
name, mark = line.strip().split(",")
total += int(mark)
print(total) # 217
A file holds three lines: Ana,72, Ben,55, Cai,90. The loop adds int(line.strip().split(",")[1]) for every line. What is the total?
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
$72 + 55 + 90 = 217$. strip() removes the "\n", split(",") separates the name from the mark, and [1] takes the mark.
Writing a file
open(path, "w")empties the file first, then writes.open(path, "a")appends to the end and keeps what was there.f.write()takes a string and adds no line break, so writef.write(name + "\n")orf.write(f"{name},{mark}\n").
Match each mode to what it does.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
"r" is the default. Choosing "w" for a log you meant to extend wipes it every run.
Errors have names
- When something goes wrong, Python raises an exception 异常, and each kind has a name:
FileNotFoundError(no such file),ValueError(int("x")),KeyError(missing dictionary key),TypeError("a" + 1),ZeroDivisionError(1 / 0). - The name is the most useful line of an error message. Read it first, then the line number above it.
Match each line to the exception it raises.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
A ValueError is the right type with a bad value; a TypeError is the wrong type for the operation.
try and except
- Put the risky lines in a
try:block and the plan for one named error in anexcept ValueError:block. If that error happens, Python jumps straight to theexceptblock. - Lines in the
tryblock after the failing line are skipped. Code after the wholetry … exceptruns as normal.
try:
print("A")
n = int("seven") # ValueError here
print("B") # skipped
except ValueError:
print("C")
print("D") # prints A, C, D
What does the A/B/C/D program print? try: prints A, runs int("seven"), prints B; except ValueError: prints C; then D is printed after the block.
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
A prints, then int("seven") raises. The rest of the try block, including B, is skipped; C runs; D runs because it is after the whole block.
Ask again until the input is good
- Put
try … exceptinside awhile True:loop. A good value reachesreturn, which leaves the loop and the function together. A bad value is caught, and the loop asks again. - The user who types
xand then4sees one message and the program carries on with4.
def read_count():
while True:
try:
return int(input("How many? "))
except ValueError:
print("Whole numbers only.")
A user types x, then 2.5, then 4 into read_count(). How many times is "Whole numbers only." printed?
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
int("x") and int("2.5") both raise ValueError, so the message appears twice. int("4") works and return ends the loop.
One outcome, several roads
- Robust code tries the normal path, names each failure it expects and gives each one a sensible fallback. The caller always gets a usable result.
- Catch only what you have a plan for. A typing mistake in your own code should still crash loudly so you can find it.

- Read the text size from
settings.txt; use 12 if the file is missing or does not hold a whole number. try:open the file andsize = int(f.read().strip()).except FileNotFoundError: size = 12andexcept ValueError: size = 12.- A file holding
16gives 16; no file gives 12; a file holdingbiggives 12. New players no longer see a crash.
Put the lines of the settings reader in order.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
The risky open-and-convert goes in try. One except can name two errors in a tuple when both get the same fallback.
Marks that slip away
- A bare
except:. It catches every error, including your own bugs, and hides them. Name the error you expect. - A huge
tryblock. Keep only the risky lines inside, so you know which line theexceptis answering. "w"when you meant"a"."w"wipes the old contents first.- Forgetting
strip()and"\n". Lines read in keep their line break; lines written out need one.
A bare except: is the safest choice, because it stops the program from ever crashing.
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
It also swallows your own bugs, such as a misspelt variable name, so they fail silently. Name the error you expect and can answer.
You've got it
with open(...)closes the file for you."r"reads,"w"empties and writes,"a"appends; strip lines you read, add"\n"to lines you write.- An exception has a name.
try … except Name:catches that one error; the rest of thetryblock is skipped. - Catch only the errors you can answer, give each a fallback, and let unexpected errors crash so you can fix them.