ไฟล์และข้อผิดพลาด
แนะนำใหม่ในบทเรียนนี้
| English | ความหมาย |
|---|---|
| exception/ekˈsepʃn/ | ข้อยกเว้น |
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
# the file holds lines like Ana,72
with open("scores.txt") as f:
for line in f:
name, mark = line.strip().split(",")
total += int(mark)
print(total) # 217
ไฟล์มีสามบรรทัด: Ana,72, Ben,55, Cai,90. ลูปเพิ่ม int(line.strip().split(",")[1]) สำหรับทุกบรรทัด ผลรวมทั้งหมดคือเท่าไร
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
$72 + 55 + 90 = 217$. strip() ลบ "\n", split(",") แยกชื่อออกจากคะแนน และ [1] ดึงคะแนนออกมา
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").
จับคู่แต่ละโหมดกับหน้าที่ของมัน
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
"r" เป็นค่าเริ่มต้น การเลือก "w" สำหรับไฟล์บันทึกที่คุณตั้งใจจะต่อเติม จะทำให้มันถูกลบออกทุกครั้งที่รัน
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.
จับคู่แต่ละบรรทัดกับข้อยกเว้นที่มันสร้างขึ้น
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
A ValueError คือประเภทที่ถูกต้องแต่มีค่าผิดพลาด; A TypeError คือประเภทที่ไม่ถูกต้องสำหรับการดำเนินการนั้น
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
โปรแกรม A/B/C/D จะพิมพ์อะไร? try: พิมพ์ A, รัน int("seven"), พิมพ์ B; except ValueError: พิมพ์ C; แล้ว D จะถูกพิมพ์หลังจากบล็อก
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
A ถูกพิมพ์ก่อน แล้ว int("seven") สร้างข้อผิดพลาด ส่วนที่เหลือของ try บล็อก รวมถึง B, จะถูกข้าม; C รัน; D รันเพราะมันอยู่หลังบล็อกทั้งหมด
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.")
ผู้ใช้พิมพ์ x, แล้ว 2.5, แล้ว 4 ลงใน read_count(). คำว่า "Whole numbers only." จะถูกพิมพ์กี่ครั้ง?
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
int("x") และ int("2.5") สร้าง ValueError เหมือนกัน ดังนั้นข้อความจึงปรากฏสองครั้ง. int("4") ทำงานได้และ return จบวงลูป
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.
เรียงลำดับบรรทัดของตัวอ่านการตั้งค่าให้ถูกต้อง
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
ส่วนเปิด-แปลงที่มีความเสี่ยงไปอยู่ใน try. One except สามารถระบุข้อผิดพลาดสองชนิดใน tuple เมื่อทั้งสองมีค่าสำรองเดียวกัน
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.
การใช้ except: ที่ว่างเปล่าเป็นการเลือกที่ปลอดภัยที่สุด เพราะจะป้องกันไม่ให้โปรแกรมเกิดข้อผิดพลาดหรือหยุดทำงาน
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
มันยังดูดกลืนข้อผิดพลาดของคุณเอง เช่น การพิมพ์ชื่อตัวแปรผิด ทำให้เกิดความล้มเหลวโดยไร้เสียง ชื่อประเภทของข้อผิดพลาดที่คุณคาดหวังและสามารถตอบได้
You've got it
with open(...)closes the file for you. Strip lines you read; add"\n"to lines you write.
| Mode | Does | File missing |
|---|---|---|
"r" |
reads | error |
"w" |
empties, then writes | creates it |
"a" |
adds to the end | creates it |
- 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.
เกิดปัญหาอะไรขึ้น? เฉพาะทีมเว็บไซต์เท่านั้นที่เห็นข้อมูลนี้