🏠 Home / Hub

📄 Python Lesson 06 — Files & Error Handling

← Back to Python Menu

1. Text File ရေးခြင်း

with open("note.txt", "w", encoding="utf-8") as file:
    file.write("Hello Python\n")
    file.write("File writing lesson")
with open() သုံးရင် file close ကို Python ကအလိုအလျောက်လုပ်ပေးတယ်။

2. Text File ဖတ်ခြင်း

with open("note.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)

3. Append Mode

with open("note.txt", "a", encoding="utf-8") as file:
    file.write("\nNew line added")

w က overwrite လုပ်တယ်။ a က အောက်ကနေထပ်ထည့်တယ်။

4. JSON File

import json

students = [
    {"name": "Aung", "age": 20},
    {"name": "Su", "age": 19}
]

with open("students.json", "w", encoding="utf-8") as file:
    json.dump(students, file, indent=2)

with open("students.json", "r", encoding="utf-8") as file:
    data = json.load(file)

print(data[0]["name"])

5. try / except

try:
    number = int(input("Enter number: "))
    print(100 / number)
except ValueError:
    print("Number ပဲထည့်ပါ")
except ZeroDivisionError:
    print("Zero နဲ့စားလို့မရပါ")
finally:
    print("Done")

6. Raise Custom Error

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("Not enough balance")
    return balance - amount

try:
    print(withdraw(1000, 1500))
except ValueError as e:
    print(e)

📌 Study Checklist