File Handling နဲ့ Error Handling
Program တွေ ရေးတဲ့အခါ Data တွေကို Memory ထဲမှာပဲ သိမ်းထားလို့ မရပါဘူး — Program ပိတ်တာနဲ့ Data တွေ ပျောက်သွားမှာမို့ File တွေထဲမှာ သိမ်းဖို့ လိုအပ်ပါတယ်။
File Handling
Section titled “File Handling”Python မှာ File တွေကို open() Function သုံးပြီး ဝင်ရောက်နိုင်ပါတယ်။ Mode (၃) မျိုး ရှိပါတယ်:
"r"— ဖတ်ဖို့ (Read)"w"— ရေးဖို့ (Write — ရှိပြီးသားဆိုရင် ဖျက်ပြီး အသစ်ရေးပါမယ်)"a"— ဆက်ထည့်ဖို့ (Append — အနောက်ကနေ ဆက်ရေးပါမယ်)
File ထဲကို ရေးခြင်း
Section titled “File ထဲကို ရေးခြင်း”# "w" Mode — ဖိုင်ကို ဆောက်ပြီး ရေးပါမယ် (ရှိပြီးသားဆိုရင် ဖျက်ပြီး ပြန်ရေးပါတယ်)with open("student.txt", "w", encoding="utf-8") as file: file.write("ကျောင်းသားစာရင်း\n") file.write("Aung Aung — 85 မှတ်\n") file.write("Su Su — 92 မှတ်\n")
print("ရေးပြီးပါပြီ!")with open(...) ကို ဘာကြောင့် သုံးမလဲ?
with Block ပြီးသွားတာနဲ့ ဖိုင်ကို အလိုအလျောက် ပိတ် (Close) ပေးပါတယ်။ ကိုယ်တိုင် file.close() ရိုက်စရာ မလိုတော့ပါဘူး — မေ့ပြီး မပိတ်မိတာမျိုး မဖြစ်နိုင်တော့ပါဘူး။
File ကနေ ဖတ်ခြင်း
Section titled “File ကနေ ဖတ်ခြင်း”import os
# ဖိုင်ရှိမရှိ အရင်စစ်ဆေးပြီးမှ ဖတ်ပါif not os.path.exists("student.txt"): print("ဖိုင် မတွေ့ပါ!")else: with open("student.txt", "r", encoding="utf-8") as file: # နည်း ၁: အကုန်တစ်ကြိမ်တည်း ဖတ်မယ် content = file.read() print(content)
with open("student.txt", "r", encoding="utf-8") as file: # နည်း ၂: တစ်ကြောင်းချင်းစီ ဖတ်မယ် for line in file: print(line.strip()) # strip() သုံးပြီး နောက်ဆုံးက \n ကို ဖြုတ်မယ်Append — ဆက်ထည့်ခြင်း
Section titled “Append — ဆက်ထည့်ခြင်း”# "a" Mode — ရှိပြီးသားအနောက်မှာ ဆက်ရေးပါမယ် (မဖျက်ပါဘူး)with open("student.txt", "a", encoding="utf-8") as file: file.write("Kyaw Kyaw — 78 မှတ်\n")JSON File — Data ကို Structure နဲ့ သိမ်းခြင်း
Section titled “JSON File — Data ကို Structure နဲ့ သိမ်းခြင်း”JSON (JavaScript Object Notation) ဆိုတာ Data ကို မည်သည့် Programming Language မဆို ဖတ်နိုင်တဲ့ Format နဲ့ သိမ်းပေးတဲ့ Standard ပါ — Python Dictionary ပုံစံနဲ့ ဆင်တူပြီး Program ၂ ခုကြား Data ဖလှယ်ဖို့၊ API တွေမှာ Response Format အဖြစ် ကမ္ဘာတစ်ဝှမ်း သုံးကြပါတယ်:
import json
# Data (Python Dictionary)student_data = { "name": "Aung Aung", "age": 20, "scores": [85, 92, 78], "active": True}
# Dictionary ကနေ JSON File ထဲ သိမ်းခြင်းwith open("student.json", "w", encoding="utf-8") as f: json.dump(student_data, f, ensure_ascii=False, indent=2){ "name": "Aung Aung", "age": 20, "scores": [85, 92, 78], "active": true}# JSON File ကနေ Python Dictionary အဖြစ် ပြန်ဖတ်ခြင်းwith open("student.json", "r", encoding="utf-8") as f: loaded = json.load(f)
print(loaded["name"]) # Aung Aungprint(loaded["scores"]) # [85, 92, 78]print(type(loaded)) # <class 'dict'>Error Handling (try / except)
Section titled “Error Handling (try / except)”Code ရေးတဲ့အခါ မထင်မှတ်ဘဲ Error တွေ တက်တတ်ပါတယ်။ ဆိုင်မှာ အချိုရည်မှာတဲ့ Customer ကို “ဒီ Flavor မရှိရင် ဒါလေးပေးလိုက်” ဆိုပြီး ကြိုပြင်ဆင်ထားသလိုမျိုး — try/except နဲ့ Error တက်ရင် ဘာလုပ်မလဲ ဆိုတာကို ကြိုသတ်မှတ်ထားနိုင်ပါတယ်။
try: # Error တက်နိုင်တဲ့ Code result = 10 / 0except ZeroDivisionError: # Error တက်ခဲ့ရင် ဒီမှာ Handle လုပ်မယ် print("သုညနဲ့ စားလို့ မရပါဘူး")Error မျိုးစုံ ကိုင်တွယ်ခြင်း
Section titled “Error မျိုးစုံ ကိုင်တွယ်ခြင်း”def get_age(): try: age = int(input("ခင်ဗျား အသက် ဘယ်လောက်လဲ? ")) result = 100 / age print(f"ခင်ဗျားဟာ {100 - age} နှစ်အကြာမှာ ၁၀၀ ပြည့်မှာပါ")
except ValueError: # int("hello") လိုမျိုး Error တက်တဲ့အခါ print("ကျေးဇူးပြု၍ ဂဏန်းသာ ထည့်ပေးပါ")
except ZeroDivisionError: # age = 0 ဖြစ်ပြီး 100/0 ဖြစ်သွားတဲ့အခါ print("အသက် 0 ဆိုတာ မဖြစ်နိုင်ပါဘူး")
except Exception as e: # မထင်မှတ်ထားတဲ့ တခြား Error တွေ print(f"အမှား ဖြစ်ပွားပါတယ်: {e}")
else: # Error မတက်ဘဲ အောင်မြင်ခဲ့ရင် ဒါ အလုပ်လုပ်ပါမယ် print("အောင်မြင်ပါတယ်!")
finally: # Error တက်တက် မတက်တက် ဒီအပိုင်းက အမြဲ Run ပါမယ် print("စစ်ဆေးမှု ပြီးဆုံးပါပြီ")
get_age()raise — ကိုယ်ပိုင် Error ဖန်တီးခြင်း
Section titled “raise — ကိုယ်ပိုင် Error ဖန်တီးခြင်း”raise ကို သုံးပြီး Input မှားယွင်းတဲ့အခါ ကိုယ်တိုင် Error ပြခိုင်းလို့ ရပါတယ်:
def set_age(age): if not isinstance(age, int): raise TypeError(f"Age ဟာ Integer ဖြစ်ရပါမယ် — {type(age)} ဖြစ်နေပါတယ်") if age < 0: raise ValueError(f"Age ဟာ 0 အောက် မဖြစ်နိုင်ပါဘူး — {age} ထည့်ထားပါတယ်") if age > 150: raise ValueError(f"Age ဟာ 150 ကျော်လို့ မရပါဘူး — {age} ထည့်ထားပါတယ်") print(f"Age သတ်မှတ်ပြီးပါပြီ: {age}")
# မှန်ကန်တဲ့ Inputset_age(20) # Age သတ်မှတ်ပြီးပါပြီ: 20
# မှားယွင်းတဲ့ Inputtry: set_age(-5) # ValueError!except ValueError as e: print(f"Error: {e}")ပေါင်းစပ် ဥပမာ — Student Record System
Section titled “ပေါင်းစပ် ဥပမာ — Student Record System”import jsonimport os
FILE = "records.json"
def load_records(): if not os.path.exists(FILE): return [] with open(FILE, "r", encoding="utf-8") as f: return json.load(f)
def save_records(records): with open(FILE, "w", encoding="utf-8") as f: json.dump(records, f, ensure_ascii=False, indent=2)
def add_student(name, score): if not name.strip(): raise ValueError("နာမည် ထည့်ပေးပါ") if not 0 <= score <= 100: raise ValueError("Score ဟာ 0 ကနေ 100 ကြားသာ ဖြစ်ရပါမယ်")
records = load_records() records.append({"name": name, "score": score}) save_records(records) print(f"✅ {name} ကို ထည့်သွင်းပြီးပါပြီ")
try: add_student("Aung Aung", 85) add_student("Su Su", 92) add_student("", 70) # ValueError!except ValueError as e: print(f"❌ {e}")