Thuta Learning
Python
IntermediateProgrammingအခြေခံ

Python File Handling

Pythonသင်ခန်းစာ 3025 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Mode r, w, a, x နဲ့ b တစ်ခုချင်းက ရှိပြီးသား file ကို ဘာလုပ်လဲ ခန့်မှန်းနိုင်ဖို့
  • with open(...) as f: ကို သုံးပြီး error ဖြစ်လည်း file ပိတ်သွားကြောင်း ရှင်းပြနိုင်ဖို့
  • Text file တိုင်းမှာ encoding="utf-8" ပေးပြီး default encoding ပြဿနာကို ရှောင်နိုင်ဖို့
  • pathlib.Path နဲ့ / operator သုံးပြီး path တွေ တည်ဆောက်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

File တစ်ခုနဲ့ အလုပ်လုပ်တာကို စာကြည့်တိုက်က စာအုပ် ငှားတာနဲ့ နှိုင်းကြည့်ပါ။ open() က စာအုပ်ကို ငှားတာပါ — ဖတ်ဖို့လား (r)၊ အသစ်ကနေ ရေးဖို့လား (w)၊ နောက်ဆုံး စာမျက်နှာမှာ ထပ်ဖြည့်ဖို့လား (a) ဆိုတာ ငှားတဲ့အချိန်မှာ ပြောရပါတယ်။ ပြီးရင် စာအုပ်ကို ပြန်အပ်ရပါတယ်၊ အဲဒါက close() ပါ။

with statement က စာကြည့်တိုက်မှူး အလိုအလျောက် ပြန်သိမ်းပေးသလိုပါပဲ။ Block ထဲက code ပြီးသွားတာနဲ့ — ပုံမှန် ပြီးသည်ဖြစ်စေ error နဲ့ ထွက်သည်ဖြစ်စေ — file ကို ပိတ်ပေးပါတယ်။ ဒါကြောင့် Python မှာ file ဖွင့်တိုင်း with ကို သုံးကြပါတယ်။

Problem → Why → Solution

ပြဿနာ: ကိုယ့်စက်မှာ အလုပ်လုပ်ပြီး သူများစက်မှာ ပျက်တဲ့ file code

အောက်က script က Linux laptop ပေါ်မှာ အဆင်ပြေပါတယ်။ အဲဒီက ထွက်လာတဲ့ notes.txt ကို Windows သုံးတဲ့ လုပ်ဖော်ကိုင်ဖက်ဆီ ပို့ပြီး encoding မပါတဲ့ open() နဲ့ပဲ ဖတ်ရင် é က စာလုံး ကြောင်ကြောင်တွေ ဖြစ်သွားတာ ဒါမှမဟုတ် UnicodeDecodeError ဖြစ်တာ ကြုံရနိုင်ပါတယ်။ ဒါ့အပြင် line 3 က division က close() မ run ခင် crash ဖြစ်လို့ file က ဖွင့်လျက် ကျန်နေပြီး ရေးထားတဲ့ line က disk ပေါ် မရောက်တာမျိုး ဖြစ်နိုင်ပါတယ်။

notes.py
f = open("notes.txt", "w")        # no encoding: depends on the machine
f.write("Café menu: naan, mohinga\n")
total = 10 / 0                      # crash: the next line never runs
f.close()

g = open("notes.txt")              # may decode with a different encoding
print(g.read())

ဘာကြောင့် ဒီလို ဖြစ်ရတာလဲ

encoding မပေးရင် Python က operating system ရဲ့ default encoding ကို သုံးပါတယ်။ Linux နဲ့ macOS မှာ အများအားဖြင့် UTF-8 ဖြစ်ပေမယ့် Windows မှာ cp1252 လို legacy code page ဖြစ်နိုင်ပါတယ်။ é လို စာလုံးတွေကို encoding တစ်မျိုးနဲ့ ရေးပြီး တခြားတစ်မျိုးနဲ့ ဖတ်ရင် ပျက်ပါတယ်။ close() ကိုလည်း ကိုယ်တိုင် ခေါ်ရတာမို့ error လမ်းကြောင်းမှာ မေ့သွားလွယ်ပါတယ်။

Core concept: path + mode + encoding + lifetime

File ဖွင့်တိုင်း ဆုံးဖြတ်ချက် လေးခု ချရပါတယ် — ဘယ် file လဲ (path)၊ ဘာလုပ်မလဲ (mode)၊ စာသားကို byte အဖြစ် ဘယ်လို ပြောင်းမလဲ (encoding)၊ ဘယ်အချိန်ထိ ဖွင့်ထားမလဲ (lifetime) ဆိုတာပါ။ open(path, mode, encoding=...) က ပထမ သုံးခုကို ဖြေပြီး with block က လေးခုမြောက်ကို ဖြေပါတယ်။

ModeFile ရှိပြီးသားဆိုရင်File မရှိရင်
"r" (default)အစကနေ ဖတ်FileNotFoundError
"w"ချက်ချင်း အလွတ် (truncate) လုပ်ပြီး ရေးအသစ် ဖန်တီး
"a"ရှိပြီးသား content နောက်မှာ ဆက်ရေးအသစ် ဖန်တီး
"x"FileExistsErrorအသစ် ဖန်တီး

Mode ထဲကို "b" ထည့်ရင် ("rb", "wb") file ကို text အဖြစ် မဟုတ်ဘဲ bytes အဖြစ် ကိုင်ပါတယ်၊ ပုံ၊ PDF၊ zip လို file တွေအတွက်ပါ။ Binary mode မှာ encoding မပေးရပါဘူး။ "+" ထည့်ရင် ("r+") ဖတ်တာရော ရေးတာရော တစ်ပြိုင်တည်း လုပ်လို့ရပေမယ့် file position ကို သတိထားရလို့ beginner တွေ ရှောင်သင့်ပါတယ်။

Text mode မှာ Python က string တွေကို encoding နဲ့ byte အဖြစ် ပြောင်းပြီး newline တွေကိုလည်း ကိုင်တွယ်ပေးပါတယ် — ဖတ်တဲ့အခါ \r\n ကို \n အဖြစ် ပြောင်းပေးလို့ Windows မှာ ရေးထားတဲ့ file ကို တခြား system တွေမှာ ဖတ်လည်း line တွေ မှန်ပါတယ်။ Default encoding က စက်ပေါ် မူတည်လို့ Python documentation ကိုယ်တိုင်က encoding ကို ကိုယ်တိုင် ပေးဖို့ အကြံပြုပါတယ်။

Write လုပ်တဲ့ data ကို Python က buffer ထဲမှာ ခဏ စုထားပြီးမှ disk ကို ရေးပါတယ်။ close() လုပ်တဲ့အခါ buffer ကို flush လုပ်ပြီး operating system ရဲ့ file handle ကိုလည်း ပြန်လွှတ်ပါတယ်။ with block က exception ဖြစ်လည်း close() ကို ခေါ်ပေးလို့ data ပျောက်တာ၊ handle ယိုစိမ့်တာကို ကာကွယ်ပါတယ်။ Path ကိုတော့ pathlib.Path(folder) / "notes.txt" လို / operator နဲ့ ဆက်ပါ၊ Windows ရဲ့ \ နဲ့ Linux ရဲ့ / ကို ကိုယ်တိုင် ရွေးစရာ မလိုပါဘူး။

pathlib မှာ file သေးသေးလေးတွေအတွက် shortcut တွေလည်း ပါပါတယ်။ path.read_text(encoding="utf-8") က ဖွင့်၊ ဖတ်၊ ပိတ် ကို call တစ်ခုတည်းနဲ့ လုပ်ပေးပြီး path.write_text(text, encoding="utf-8") က ရေးဖို့အတွက် အလားတူပါပဲ။ Kilobyte အနည်းငယ်ပဲ ရှိတဲ့ config file တွေအတွက် အကောင်းဆုံးပါ။ Log ဒါမှမဟုတ် export လို ကြီးလာနိုင်တဲ့ file တွေအတွက်တော့ open() နဲ့ line တစ်ကြောင်းချင်း ဒါမှမဟုတ် chunk လိုက် process လုပ်ပါ၊ memory သုံးစွဲမှု မတက်တော့ပါဘူး။

မှတ်ထားရမယ့် ပုံစံ
  1. Path ကို Path() နဲ့ တည်ဆောက်
  2. Mode နဲ့ encoding ပေးပြီး open
  3. with block ထဲမှာ ဖတ်/ရေး
  4. Block ပြီးတာနဲ့ အလိုအလျောက် close

File object ကို with block အပြင်မှာ မသုံးပါနဲ့ — အဲဒီအချိန်မှာ ပိတ်ပြီးသားပါ။

အထွေထွေ ပုံစံ

python
from pathlib import Path

path = Path(folder) / "file_name.txt"

with open(path, "mode", encoding="utf-8") as f:   # mode: r, w, a or x
    data = f.read()        # or f.write(text), or: for line in f
# the file is closed here, even after an exception

with open(path, "rb") as f:                        # binary: no encoding
    raw = f.read()

Path ကို / နဲ့ ဆက်ပြီး with open(...) as f: ထဲမှာ အလုပ်လုပ်ပါ။ Text mode မှာ encoding ပေးပြီး binary mode ("rb", "wb") မှာ encoding မပေးပါဘူး။ Indent ပြီးသွားတဲ့ နေရာမှာ file က ပိတ်ပြီးသားပါ။

Example: ရေး၊ ဆက်ရေး၊ ပြန်ဖတ်

ဒီ example က tempfile.TemporaryDirectory() ထဲမှာ အလုပ်လုပ်ပါတယ်။ Folder ယာယီတစ်ခု ဖန်တီးပြီး block ပြီးတာနဲ့ အထဲက file တွေနဲ့အတူ ဖျက်ပေးလို့ သင့်ရဲ့ project folder ထဲ ဘာမှ မကျန်ပါဘူး။ Mode သုံးမျိုးကို တစ်ဆက်တည်း သုံးထားပြီး f.closed နဲ့ with က file ကို ပိတ်ပေးကြောင်း စစ်ထားပါတယ်။

file_basics.py
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "notes.txt"

    with open(path, "w", encoding="utf-8") as f:   # "w": create or overwrite
        f.write("Hello, this is a new file.\n")
        f.write("This is the second line.\n")
    print(f"Created {path.name}, closed: {f.closed}")

    with open(path, "a", encoding="utf-8") as f:   # "a": add to the end
        f.write("Appended line.\n")

    with open(path, "r", encoding="utf-8") as f:   # "r": read (the default)
        for number, line in enumerate(f, start=1):
            print(number, line.rstrip("\n"))

    print(f"Exists inside the block: {path.exists()}")

print(f"Exists after cleanup: {path.exists()}")

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Line 5path = Path(tmp) / "notes.txt"

    / operator က folder နဲ့ file name ကို operating system နဲ့ ကိုက်တဲ့ separator နဲ့ ဆက်ပေးပါတယ်။ path.name က "notes.txt" ပဲ ဖြစ်လို့ output ထဲမှာ temp folder ရဲ့ path အရှည်ကြီး မပေါ်ပါဘူး။

  2. Lines 7-10with open(path, "w", encoding="utf-8") as f: # "w": create or overwrite

    "w" က file မရှိလို့ အသစ် ဖန်တီးပါတယ်။ write() က newline ကို အလိုအလျောက် မထည့်လို့ \n ကို ကိုယ်တိုင် ရေးထားပါတယ်။ Block ပြင်ပ line 10 မှာ f.closed က True ဖြစ်နေပါပြီ။

  3. Lines 12-13with open(path, "a", encoding="utf-8") as f: # "a": add to the end

    "a" က ရှိပြီးသား line နှစ်ကြောင်းကို မထိဘဲ အဆုံးမှာ ဆက်ရေးပါတယ်။ ဒီနေရာမှာ "w" သုံးမိရင် ပထမ line နှစ်ကြောင်း ပျောက်သွားပါမယ်။

  4. Lines 15-17for number, line in enumerate(f, start=1):

    File object ကို for loop နဲ့ တိုက်ရိုက် iterate လုပ်ရင် line တစ်ကြောင်းချင်း ရပါတယ်။ Line တိုင်းမှာ \n ပါလာလို့ rstrip("\n") နဲ့ ဖြုတ်ပါတယ်၊ မဖြုတ်ရင် line ကြားမှာ blank line တွေ ပေါ်ပါမယ်။

  5. Lines 19-21print(f"Exists after cleanup: {path.exists()}")

    TemporaryDirectory block အတွင်းမှာ file ရှိပေမယ့် block ပြီးတာနဲ့ folder တစ်ခုလုံး ဖျက်ခံရလို့ False ဖြစ်ပါတယ်။

You should see
Created notes.txt, closed: True
1 Hello, this is a new file.
2 This is the second line.
3 Appended line.
Exists inside the block: True
Exists after cleanup: False

File error တွေကို နာမည်နဲ့ ခွဲသိပါ

File code မှာ ကြုံရတတ်တဲ့ exception တွေက သီးခြား အမျိုးအစားတွေပါ — file မရှိရင် FileNotFoundError၊ ခွင့်ပြုချက် မရှိရင် PermissionError၊ "x" mode မှာ file ရှိနေရင် FileExistsError၊ encoding မှားရင် UnicodeDecodeError ပါ။ ပထမ သုံးခုက OSError ရဲ့ subclass တွေ ဖြစ်ပါတယ်။ အောက်က code က latin-1 နဲ့ ရေးထားတဲ့ file ကို UTF-8 နဲ့ ဖတ်ရင် ဘာဖြစ်လဲ ပြပါတယ်။

file_errors.py
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    folder = Path(tmp)
    try:
        with open(folder / "missing.txt", encoding="utf-8") as f:
            f.read()
    except FileNotFoundError as err:
        print(f"{type(err).__name__}: {Path(err.filename).name}")

    legacy = folder / "legacy.txt"
    legacy.write_bytes("café".encode("latin-1"))     # bytes b'caf\xe9'
    try:
        legacy.read_text(encoding="utf-8")
    except UnicodeDecodeError as err:
        print(f"UnicodeDecodeError at byte {err.start}")
    print(legacy.read_text(encoding="latin-1") == "café")

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Data pipeline တွေ၊ report generator တွေနဲ့ config loader တွေ အားလုံးက file handling ပေါ်မှာ အခြေခံပါတယ်။ ပုံမှန် ပုံစံက input file ကို UTF-8 နဲ့ line တစ်ကြောင်းချင်း ဖတ်၊ line တိုင်းကို validate လုပ်ပြီး output file ကို ရေးတာပါ။ File ကြီးတွေကို တစ်ခါတည်း memory ထဲ မတင်ဘဲ stream လုပ်တာကြောင့် gigabyte ရှိတဲ့ log file တွေကိုလည်း RAM နည်းနည်းနဲ့ process လုပ်နိုင်ပါတယ်။

Production code မှာ error တွေကို အမျိုးအစားအလိုက် ခွဲကိုင်ပါတယ်။ FileNotFoundError ဆိုရင် user ကို path စစ်ခိုင်းတဲ့ message ပြပြီး PermissionError ဆိုရင် ဘယ် account နဲ့ run နေလဲ log ထုတ်ပါတယ်။ UnicodeDecodeError ဆိုရင်တော့ file ကို ဘယ် encoding နဲ့ ထုတ်ထားလဲ data ပေးတဲ့သူကို မေးရပါတယ်။ Test တွေမှာတော့ ဒီ lesson ရဲ့ example လိုပဲ temporary directory ထဲမှာ file တွေ ဖန်တီးလို့ test တစ်ခုချင်း သန့်ရှင်းပြီး တစ်ခုနဲ့တစ်ခု မထိခိုက်ပါဘူး၊ pytest ရဲ့ tmp_path fixture က ဒီအလုပ်ကို လုပ်ပေးပါတယ်။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. ဖတ်ဖို့ ရည်ရွယ်ပြီး "w" နဲ့ ဖွင့်တာ

open(path, "w") က write() တစ်ခါမှ မခေါ်ရသေးခင် ဖွင့်လိုက်တဲ့ အချိန်မှာတင် file ကို အလွတ် လုပ်ပစ်ပါတယ်။ ဖတ်ချင်ရင် "r" (ဒါမှမဟုတ် mode မပေး) သုံးပြီး ဆက်ရေးချင်ရင် "a" သုံးပါ။

2. encoding မပေးတာ

open("data.txt") က ကိုယ့်စက်မှာ အလုပ်လုပ်ပေမယ့် default encoding မတူတဲ့ စက်မှာ UnicodeDecodeError ဒါမှမဟုတ် စာလုံးပျက်တွေ ထွက်နိုင်ပါတယ်။ Text file တိုင်းမှာ encoding="utf-8" ပေးပါ။

3. with block အပြင်မှာ file ကို သုံးတာ

with block ပြီးမှ f.read() ခေါ်ရင် "I/O operation on closed file" ValueError ရပါတယ်။ လိုတဲ့ data ကို block ထဲမှာ variable ထဲ သိမ်းပြီးမှ အပြင်မှာ သုံးပါ။

4. Windows path ကို ရိုးရိုး string နဲ့ ရေးတာ

open("C:\new\data.txt") က ကိုယ်ထင်တဲ့ file ကို မဖွင့်ပါဘူး — ရိုးရိုး string ထဲက \n က newline character ဖြစ်သွားလို့ပါ။ r"C:\new\data.txt" လို raw string၊ forward slash ဒါမှမဟုတ် Path("C:/new") / "data.txt" ကို သုံးပါ။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • Program ထဲမှာ path တွေကို str အစား Path object အဖြစ် ကိုင်ထားပြီး open() ကို ခေါ်တဲ့ နေရာမှာပဲ သုံးပါ။
  • Test နဲ့ စမ်းသပ်ချက်တွေကို tempfile ဒါမှမဟုတ် pytest ရဲ့ tmp_path ထဲမှာပဲ run ပါ၊ project folder ထဲ file အမှိုက်တွေ မကျန်စေနဲ့။
  • Script ရဲ့ လက်ရှိ working directory ကို အားမကိုးဘဲ Path(__file__).parent ကနေ relative path တွေ တည်ဆောက်ပါ။

Mini challenge

Mini challenge: file တစ်ခုကို စာလုံးကြီးနဲ့ ကူးပါ

Source file ကို line တစ်ကြောင်းချင်း ဖတ်ပြီး စာလုံးကြီး (upper case) ပြောင်းကာ target file ထဲ ရေးတဲ့ copy_upper() ကို ရေးပါ။ Temporary directory ထဲမှာပဲ စမ်းပါ။

  • File နှစ်ခုလုံးကို with နဲ့ encoding="utf-8" နဲ့ ဖွင့်ရမယ်
  • File တစ်ခုလုံးကို read() နဲ့ မဖတ်ဘဲ line တစ်ကြောင်းချင်း process လုပ်ရမယ်
  • ကူးခဲ့တဲ့ line အရေအတွက်ကို return ပြန်ရမယ်
  • Source မရှိရင် FileNotFoundError ကို ဖမ်းပြီး message ပြရမယ်
copy_upper.py
import tempfile
from pathlib import Path


def copy_upper(source: Path, target: Path) -> int:
    """Copy source to target in upper case and return the number of lines."""
    # TODO: open source for reading and target for writing, both as utf-8
    # TODO: loop over the source lines, write each one upper-cased, count them
    ...


with tempfile.TemporaryDirectory() as tmp:
    folder = Path(tmp)
    # TODO: create input.txt with three short lines
    # TODO: call copy_upper(), print the count and the new file's content
    # TODO: call it with a missing source and print a friendly message

ရလဒ်: Program က ဒီလို print ထုတ်ရပါမယ်: Copied 3 lines APPLES BANANAS CHERRIES Source file not found, nothing copied

အရိပ်အမြွက် ကြည့်ရန်

with ( open(...) as src, open(...) as dst, ): လို ကွင်းထဲမှာ context manager နှစ်ခု တွဲရေးလို့ ရပါတယ် (Python 3.10+)။ line.upper() က \n ကို မပြောင်းလို့ ထပ်မထည့်ရပါဘူး။

အဖြေ ကြည့်ရန်
copy_upper.py
import tempfile
from pathlib import Path


def copy_upper(source: Path, target: Path) -> int:
    """Copy source to target in upper case and return the number of lines."""
    count = 0
    with (
        open(source, "r", encoding="utf-8") as src,
        open(target, "w", encoding="utf-8") as dst,
    ):
        for line in src:
            dst.write(line.upper())
            count += 1
    return count


with tempfile.TemporaryDirectory() as tmp:
    folder = Path(tmp)
    source = folder / "input.txt"
    source.write_text("apples\nbananas\ncherries\n", encoding="utf-8")

    lines = copy_upper(source, folder / "output.txt")
    print(f"Copied {lines} lines")
    print((folder / "output.txt").read_text(encoding="utf-8"), end="")

    try:
        copy_upper(folder / "nope.txt", folder / "nope_upper.txt")
    except FileNotFoundError:
        print("Source file not found, nothing copied")

Quick Quiz 1 / 3

report.txt မှာ line 10 ကြောင်း ရှိပါတယ်။ with open("report.txt", "w", encoding="utf-8") as f: pass ကို run ပြီးရင် file ထဲ ဘာကျန်မလဲ။

Quick Quiz 2 / 3

with open(p, encoding="utf-8") as f: data = f.read() ပြီးနောက် block အပြင်မှာ f.closed က ဘာလဲ။

Quick Quiz 3 / 3

PNG ပုံ file တစ်ခုကို ကူးဖို့ ဘယ် open() call က မှန်လဲ။

မှတ်ထားရမယ့် အချက်များ

  • File ဖွင့်တိုင်း path, mode, encoding, lifetime လေးခုကို ဆုံးဖြတ်ရပါတယ်။
  • "r" ဖတ်၊ "w" အလွတ်လုပ်ပြီး ရေး၊ "a" ဆက်ရေး၊ "x" မရှိမှ ဖန်တီး၊ "b" က bytes ပါ။
  • with open(...) as f: က error ဖြစ်လည်း file ကို ပိတ်ပေးပါတယ်။
  • Text file တိုင်းမှာ encoding="utf-8" ပေးပြီး path တွေကို pathlib.Path နဲ့ / နဲ့ တည်ဆောက်ပါ။

Python Documentation — Reading and Writing Files — Python Software Foundation

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Python File Handling | Thuta Learning